大话设计-策略模式
记录大话设计的学习。大话设计模式pdf分享:https://pan.baidu.com/s/11h9x-4RffXydf3GFH5_y7g 提取码:x5c3 。
上一篇通过超市优惠结账的例子学习了算法的封装和产生实例的简单工厂。这一篇在简单工厂上继续加工,让它变成一种策略模式。
每一种优惠算法都是一个具体的策略,它们抽象出来一个共同的策略就是返回结账数额。通过CashContext创建实例,调用策略,简化了使用算法类和算法类之间的耦合。在这里客户端不同知道具体使用了哪种策略,甚至是结账金额是否通过了几种策略的混合计算(举例:传入"满900减100;8折",就使用了CashRebate和CashReturn)。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { var cashContext = new CashContext("8折"); var result = cashContext.GetResult(900); } } public class CashContext { CashSuper cashSuper; public CashContext(string type) { switch (type) { case "满300减50": cashSuper = new CashReturn(300d, 50d); break; case "8折": cashSuper = new CashRebate(0.8d); break; default: cashSuper = new CashNormal(); break; } } public double GetResult(double money) { return cashSuper.AcceptCash(money); } } public abstract class CashSuper { public abstract double AcceptCash(double money); } public class CashNormal : CashSuper { public override double AcceptCash(double money) { return money; } } public class CashRebate : CashSuper { private double rebate; public CashRebate(double rebate) { this.rebate = rebate; } public override double AcceptCash(double money) { return money * rebate; } } public class CashReturn : CashSuper { private double moneyCondition; private double moneyReturn; public CashReturn(double condition, double @return) { moneyCondition = condition; moneyReturn = @return; } public override double AcceptCash(double money) { if (money >= moneyCondition) { return money - ((money / moneyCondition) * moneyReturn); } else { return money; } } } }
量变会引起质变。