设计模式_策略模式
/// <summary> /// 抽象算法 /// </summary> public abstract class Strategy { public abstract void AlgorithmInterface(); } public class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法A实现"); } } public class ConcreteStrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法B实现"); } } public class ConcreteStrategyC : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法C实现"); } } public class Context { Strategy _strategy; /// <summary> /// 初始化时,传入具体的策略对象 /// </summary> /// <param name="strategy"></param> public Context(Strategy strategy) { _strategy = strategy; } public void ContextInterface() { _strategy.AlgorithmInterface(); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); /* * 商场促销---策略模式 */ //策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之前可以互相替换,此模式让算法的变化,不会影响到使用算法的客户 Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); context = new Context(new ConcreteStrategyC()); context.ContextInterface(); Console.Read(); }