策略模式(Strategy):它定義了算法家族,分別封裝起來,讓它們這件可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶。
namespace StrategyDesignPattern { //抽象算法類 public abstract class Strategy { //算法方法 public abstract void AlgorithmInterface(); } //具體算法A public class ConcreateStrategyA:Strategy { //算法A實現方法 public override void AlgorithmInterface() { Console.WriteLine("算法A實現"); } } //具體算法B public class ConcreateStrategyB : Strategy { //算法A實現方法 public override void AlgorithmInterface() { Console.WriteLine("算法B實現"); } } //上下文 public class Context { Strategy Strategy; public Context(Strategy strategy) { Strategy = strategy; } //上下文接口 public void ContextInterface() { Strategy.AlgorithmInterface(); } } }View Code
測試代碼:
public void StrategyTest() { Context context; context = new Context(new ConcreateStrategyA()); context.ContextInterface(); context = new Context(new ConcreateStrategyB()); context.ContextInterface(); }
策略與簡單工廠結合:
public Context(string type) { switch(type) { case "A": Strategy = new ConcreateStrategyA(); break; case "B": Strategy = new ConcreateStrategyB(); break; } }