策略模式

策略模式:定义一系列算法的方法,才概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有算法,减少了各种算法类与使用算法类之间的耦合。
 
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
 
策略模式的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中,然后调用算法即可
 
 
 
posted @ 2017-04-26 14:13  小浩学长  阅读(125)  评论(0编辑  收藏  举报