标签:
定义一个算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
一、算法基类
1 /// <summary> 2 /// 抽象算法类 3 /// </summary> 4 public abstract class Strategy 5 { 6 /// <summary> 7 /// 算法方法 8 /// </summary> 9 public abstract void AlgorithmicInterface(); 10 11 }
二、算法实现(A、B)
1 /// <summary> 2 /// 策略方法A 3 /// </summary> 4 public class ConcreteStrategyA : Strategy 5 { 6 public override void AlgorithmicInterface() 7 { 8 Console.Write("策略方法A"); 9 } 10 } 11 12 /// <summary> 13 /// 策略方法B 14 /// </summary> 15 public class ConcreteStrategyB : Strategy 16 { 17 public override void AlgorithmicInterface() 18 { 19 Console.Write("策略方法B"); 20 } 21 }
三、调度器
1 public class Context 2 { 3 Strategy strategy = null; 4 public Context(Strategy strategy) 5 { 6 this.strategy = strategy; 7 } 8 9 public void ContextInterface() 10 { 11 this.strategy.AlgorithmicInterface(); 12 } 13 }
四、执行
1 /// <summary> 2 /// 策略模式 3 /// </summary> 4 public class DoStrategy : DesignPattern 5 { 6 public override void ExeFun() 7 { 8 Context context = null; 9 context = new Context(new ConcreteStrategyA()); 10 context.ContextInterface(); 11 } 12 }
标签:
原文地址:http://www.cnblogs.com/pasture-code/p/4560471.html