策略模式可以认为是根据输入要求通过多种方法得到结果,对中间计算过程的封装,可参考:http://www.cnblogs.com/chenssy/p/3295643.html,总结已经很好了,这里贴一张策略模式的结构图,用startuml自己画的:
生成c#代码为:
using System.Windows.Forms; namespace TestFormSington { public abstract class Strategy { public abstract void AlgorithmInterface(); } public class Context { public Strategy strategy; public Context(Strategy _strategy) { strategy = _strategy; } public void ContextInterface() { strategy.AlgorithmInterface(); } } public class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { MessageBox.Show("ConcreteStrategyA"); } } public class ConcretStrategyC : Strategy { public override void AlgorithmInterface() { MessageBox.Show("ConcretStrategyC"); } } public class ConcretStrategyB : Strategy { public override void AlgorithmInterface() { MessageBox.Show("ConcretStrategyB"); } } }
引用为:
Context context = new Context(new ConcreteStrategyA()); context.ContextInterface();