策略模式
策略模式:定義一系列算法的方法,才概念上看,所有這些算法完成的都是相同的工作,只是實現不同,它可以以相同的方式調用所有算法,減少了各種算法類與使用算法類之間的耦合。
策略模式就是用來封裝算法的,但在實踐中,我們發現可以用它來封裝任何類型的規則,只要在分析過程中聽到需要在不同時間應用不同的業務規則,就可以考慮使用策略模式處理這種變化的可能性。
策略模式的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中,然后調用算法即可。

浙公網安備 33010602011771號