标签:
策略模式包含三个角色:
Strategy类(抽象策略)
abstract class Strategy { //算法方法 public abstract void AlgorithmInterface(); }
ConcreteStrategy类(具体策略)
//具体算法A class ConcreteStrategyA:Strategy { //算法A实现方法 public override void AlgorithmInterface(); { Console.WriteLine("算法A实现"); } } //具体算法B class ConcreteStrategyB:Strategy { //算法B实现方法 public override void AlgorithmInterface(); { Console.WriteLine("算法B实现"); } } //具体算法C class ConcreteStrategyC:Strategy { //算法C实现方法 public override void AlgorithmInterface(); { Console.WriteLine("算法C实现"); } }
Context类(环境)
//上下文 class Context { Strategy strategy; public Context(Strategy stratety) //初始化时,传入具体的策略对象 { this.strategy=strategy; } //上下文接口 public void ContextInteface() //根据具体的策略对象,调用其算法的方法 { strategy.AlgorithmInterface(); } }
客户端代码
static void Main(string[] args) { Context context; //由于实例化不同的策略,所以最终在调用context.ContextInterface()时,所获得的结果不尽相同 context=new Context(new ConcreteStrategyA()); context.ContextInterface(); context=new Context(new ConcreteStrategyB()); context.ContextInterface(); context=new Context(new ConcreteStrategyC()); context.ContextInterface(); Console.Read(); }
标签:
原文地址:http://www.cnblogs.com/shanoon/p/5452209.html