商城打折促销活动的实现:
static void Main(string[] args) { Context context = null; string str=Console.ReadLine(); switch(str) { case "正常收费": context = new Context(new ConcreteStragegyA()); break; case "打8折": context = new Context(new ConcreteStragegyB("0.8")); break; case "满300优惠100": context = new Context(new ConcreteStragegyC("300","100")); break; } context.GetResult(300); Console.ReadKey(); } /// <summary> /// 抽象算法类 /// </summary> public abstract class Strategy { /// <summary> /// 算法方法 /// </summary> public abstract double AligorithmInterface(double money); } /// <summary> /// 不打折 /// </summary> public class ConcreteStragegyA:Strategy { public override double AligorithmInterface(double money) { return money; } } /// <summary> /// 打折 /// </summary> public class ConcreteStragegyB:Strategy { private double _moneyRebate = 1d; public ConcreteStragegyB(string moneyRate) { this._moneyRebate = double.Parse(moneyRate); } public override double AligorithmInterface(double money) { return money * _moneyRebate; } } /// <summary> /// 返利类 /// </summary> public class ConcreteStragegyC : Strategy { private double _moneyCondition = 0; private double _moneyRetrun = 0; public ConcreteStragegyC(string moneyCondition,string moneyReturn) { this._moneyCondition = double.Parse(moneyCondition); this._moneyRetrun = double.Parse(moneyReturn); } public override double AligorithmInterface(double money) { double result = money; if(money>=_moneyCondition) { result = money - Math.Floor(money / _moneyCondition) * _moneyRetrun; } return result; } } /// <summary> /// 维护类 /// </summary> public class Context { public Strategy super; public Context(Strategy stragety) { super = stragety; } public double GetResult(double moeny) { return super.AligorithmInterface(moeny); } }
备注:策略模式定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式然后算法的变换,不会影响到使用算法的客户。
但是这个还是在客户端判断去判断哪一个算法,我们怎么去把判断的过程从客户端移走呢?
策略和工厂模式的结合
修改Context类:
/// <summary> /// 维护类升级版 /// </summary> public class ContexPro { Strategy strategy = null; public ContexPro(string type) { Strategy cs = null; switch (type) { case "正常收费": strategy = new ConcreteStragegyA(); break; case "打8折": strategy = new ConcreteStragegyB("0.8"); break; case "满300返回100": strategy = new ConcreteStragegyC("300", "100"); break; } } public double GetResult(double money) { return strategy.AligorithmInterface(money); } }
策略模式和简单工厂的结合,让客户端只认识一个ContextPro对象就可以了,连算法的父类Strategy客户端都不认识。彻底的解耦合。
解析:策略模式是一种定义一系列算法的方法,从概念上讲,所以有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调 用所有的算法,减少了各种算法类与使用算法类之间的耦合。
当不同的行为都堆砌在一个类中,我们就很难避免有分支语句去判断到底要执行哪一个行为,我们就将这些一个个行为封装到一个个Stratagy中。