这个模式是对模板方法的简单包装,可以看到,只是多了一个Context类这个包装器。
我也设计模式——23.Strategy


以上UML图的代码很好实现,关键是Client如何使用Context类:

我也设计模式——23.Strategy            Strategy s = new ConcreteStrategyA();
我也设计模式——23.Strategy
我也设计模式——23.Strategy            Context context 
= new Context();
我也设计模式——23.Strategy            context.Strategy 
= s;
我也设计模式——23.Strategy            context.ContextInterface();

客户端必须知道所有的策略类,从而会造成很多策略类,这是该模式的缺点。

基于委托的策略模式,可以解除Context与Strategy的耦合,于是ConcreteStrategyA与ConcreteStrategyB可以不是相同的父类。

我也设计模式——23.Strategy    public delegate void strategy();
我也设计模式——23.Strategy
我也设计模式——23.Strategy    
public class ContextUseingDelegate
    }

于是在Client这么调用代码:

我也设计模式——23.Strategy            StrategyClassA sa = new StrategyClassA();
我也设计模式——23.Strategy
我也设计模式——23.Strategy            ContextUseingDelegate cud 
= new ContextUseingDelegate();
我也设计模式——23.Strategy            cud.myStrategy 
+= new strategy(sa.ConcreteStrategyA);
我也设计模式——23.Strategy            cud.myStrategy 
+= new strategy(StrategyClassB.ConcreteStrategyB);
我也设计模式——23.Strategy            cud.ContextInterface();

 

相关文章:

  • 2021-06-29
  • 2021-07-26
  • 2022-12-23
  • 2021-05-31
  • 2022-12-23
  • 2021-07-09
  • 2022-02-03
  • 2021-12-31
猜你喜欢
  • 2021-12-22
  • 2021-08-17
  • 2021-07-19
  • 2021-11-27
  • 2022-02-25
  • 2022-12-23
相关资源
相似解决方案