策略模式

策略模式:定义一系列算法的方法,才概念上看,全部这些算法完成的都是相同的工做,只是实现不一样,它能够以相同的方式调用全部算法,减小了各类算法类与使用算法类之间的耦合。
 
策略模式就是用来封装算法的,但在实践中,咱们发现能够用它来封装任何类型的规则,只要在分析过程当中听到须要在不一样时间应用不一样的业务规则,就能够考虑使用策略模式处理这种变化的可能性。
 
策略模式的Strategy类层次为Context定义了一系列 

  

abstract class Strategy{
     public abstract void AlgorithmInterface();
}
class StrategyA extend Strategy{
     public AlgorithmInterface(){ //A实现 };
}
class StrategyB extend Strategy{
     public AlgorithmInterface(){ //B实现 };
}
class StrategyC extend Strategy{
     public AlgorithmInterface(){ //C实现 };
}
class Context(){
     Strategy strategy;
     public Context(bufferType:Srting){      //能够搭配简单工厂模式一块儿使用
          var strategy = null;
       switch(bufferType){
        case "a":strategy = new StrategyA();
        case "b":strategy = new StrategyB();
        case "c":strategy = new StrategyC();
      }
       this.strategy = buffer;
     }
     public ContextInterface(){
          this.strategy.AlgorithmInterface();
     }
}

class Main{
  Context context = new Context("a");
  context.ContextInterface();
}

  

//在客户端使用只须要根据客户须要实例化不一样的Strategy类型传入Context中,而后调用算法便可
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息