using System; using System.Collections.Generic; using System.Text; ///Strategy(策略)模式又称Policy模式,用于定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。 ///add by jzh 2007-04-29 namespace DesignPattern { /// <summary> /// strategy 定义所有支持的算法的公共接口. /// context使用这个接口来调用某concreteStrategy定义的算法 /// </summary> abstract class Strategy { abstract public void DoAlgorithm(); } /// <summary> /// 具体策略,以strategy接口实现某具体算法 /// </summary> class FirstStrategy : Strategy { override public void DoAlgorithm() { Console.WriteLine("第一个策略"); } } class SecondStrategy : Strategy { override public void DoAlgorithm() { Console.WriteLine("第二个策略"); } } /// <summary> /// 上下文,用一个ConcreteStrategy对象来配置, /// 维护一个对strategy对象的引用, /// 可定义一个接口来让strategy访问它的数据 /// </summary> class Context { Strategy s; public Context(Strategy strat) { s = strat; } public void DoWork() { Console.WriteLine("执行动作"); } public void DoStrategyWork() { s.DoAlgorithm(); } } public class Client { public static void Main(string[] args) { FirstStrategy firstStrategy = new FirstStrategy(); Context c = new Context(firstStrategy); c.DoWork(); c.DoStrategyWork(); Console.ReadLine(); } } }