策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
策略模式结构图:
策略模式实现代码:
abstract class Strategy{ public abstract void AlgorithmInterface(); }class ConcreStrategyA:Strategy{ public override void AlgorithmInterface(); { console.WriteLine("算法A实现"); }}class ConcreStrategyB:Strategy{ public override void AlgorithmInterface(); { console.WriteLine("算法B实现"); }}class ConcreStrategyC:Strategy{ public override void AlgorithmInterface(); { console.WriteLine("算法C实现"); }}class Context{ Strategy strategy; public Context(Strategy strategy) { this.strategy=strategy; } public void ContexInterface() { strategy.AlgorithmInterface(); }}public void Main(string[] args){ Context context; context =new Context(new ConcreStrategyA()); context.ContexInterface(); context =new Context(new ConcreStrategyB()); context.ContexInterface(); context =new Context(new ConcreStrategyC()); context.ContexInterface(); Console.Read(); }