我也设计模式——23.Strategy
这个模式是对模板方法的简单包装,可以看到,只是多了一个Context类这个包装器。
以上UML图的代码很好实现,关键是Client如何使用Context类:
Strategy s = new ConcreteStrategyA();
Context context = new Context();
context.Strategy = s;
context.ContextInterface();
Context context = new Context();
context.Strategy = s;
context.ContextInterface();
客户端必须知道所有的策略类,从而会造成很多策略类,这是该模式的缺点。
基于委托的策略模式,可以解除Context与Strategy的耦合,于是ConcreteStrategyA与ConcreteStrategyB可以不是相同的父类。
public delegate void strategy();
public class ContextUseingDelegate
{
public strategy myStrategy;
public void ContextInterface()
{
myStrategy();
}
}
public class StrategyClassA
{
public void ConcreteStrategyA() { }
}
public static class StrategyClassB
{
public static void ConcreteStrategyB() { }
}
public class ContextUseingDelegate
{
public strategy myStrategy;
public void ContextInterface()
{
myStrategy();
}
}
public class StrategyClassA
{
public void ConcreteStrategyA() { }
}
public static class StrategyClassB
{
public static void ConcreteStrategyB() { }
}
于是在Client这么调用代码:
StrategyClassA sa = new StrategyClassA();
ContextUseingDelegate cud = new ContextUseingDelegate();
cud.myStrategy += new strategy(sa.ConcreteStrategyA);
cud.myStrategy += new strategy(StrategyClassB.ConcreteStrategyB);
cud.ContextInterface();
ContextUseingDelegate cud = new ContextUseingDelegate();
cud.myStrategy += new strategy(sa.ConcreteStrategyA);
cud.myStrategy += new strategy(StrategyClassB.ConcreteStrategyB);
cud.ContextInterface();