定義一系列算法,將它們一個個封裝起來,而且使它們能夠互相替換,該模式使得算法可獨立於使用它的客戶而變化。 --《設計模式》GoF算法
1,抽象策略角色(Strategy):定義公共接口,Context上下文使用這個接口調用不一樣的算法,通常使用接口實現(也可使用抽象類)。設計模式
2,具體策略角色(ConcreteStrategy):接口的實現,實現具體的算法。app
3,上下文角色(Context):維護一個策略對象的引用,並用定義容許策略訪問其數據的接口。ide
using System; namespace DoFactory.GangOfFour.Strategy.Structural { /// <summary> /// MainApp startup class for Structural /// Strategy Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Strategy' abstract class /// </summary> abstract class Strategy { public abstract void AlgorithmInterface(); } /// <summary> /// A 'ConcreteStrategy' class /// </summary> class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyA.AlgorithmInterface()"); } } /// <summary> /// A 'ConcreteStrategy' class /// </summary> class ConcreteStrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyB.AlgorithmInterface()"); } } /// <summary> /// The 'Context' class /// </summary> class Context { private Strategy _strategy; // Constructor public Context(Strategy strategy) { this._strategy = strategy; } public void ContextInterface() { _strategy.AlgorithmInterface(); } } }
運行結果:this