策略模式

策略模式:定義一系列算法的方法,才概念上看,全部這些算法完成的都是相同的工做,只是實現不一樣,它能夠以相同的方式調用全部算法,減小了各類算法類與使用算法類之間的耦合。
 
策略模式就是用來封裝算法的,但在實踐中,咱們發現能夠用它來封裝任何類型的規則,只要在分析過程當中聽到須要在不一樣時間應用不一樣的業務規則,就能夠考慮使用策略模式處理這種變化的可能性。
 
策略模式的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中,而後調用算法便可
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息