策略模式跟简单工厂模式大致相同,不同的是策略模式中的上下文类会包含策略父类。
代码1:策略抽象部分
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 策略模式 { /// <summary> /// 现金收取父类 /// </summary> abstract class BaseCash { //抽象方法:收取现金,参数为原价,返回为当前价 public abstract double acceptCash(double money); } /// <summary> /// 打折 /// </summary> class RebateCash : BaseCash { private double moneyRebate = 1d; //初始化时,必需要输入折扣率,如八折,就是0.8 public RebateCash(string moneyRebate) { this.moneyRebate = double.Parse(moneyRebate); } public override double acceptCash(double money) { return money * moneyRebate; } } /// <summary> /// 正常收费 /// </summary> class NormalCash : BaseCash { public override double acceptCash(double money) { return money; } } //返利收费,继承CashSuper class ReturnCash : BaseCash { private double moneyCondition = 0.0d; private double moneyReturn = 0.0d; //初始化时必须要输入返利条件和返利值,比如满300返100,则moneyCondition为300,moneyReturn为100 public ReturnCash(string moneyCondition, string moneyReturn) { this.moneyCondition = double.Parse(moneyCondition); this.moneyReturn = double.Parse(moneyReturn); } public override double acceptCash(double money) { double result = money; //若大于返利条件,则需要减去返利值 if (money >= moneyCondition) result = money - Math.Floor(money / moneyCondition) * moneyReturn; return result; } } }
代码2:策略容器部分
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 策略模式 { //现金收取工厂 class CashContext { BaseCash cs = null; //根据条件返回相应的对象 public CashContext(string type) { switch (type) { case "正常收费": NormalCash cs0 = new NormalCash(); cs = cs0; break; case "满300返100": ReturnCash cr1 = new ReturnCash("300", "100"); cs = cr1; break; case "打8折": RebateCash cr2 = new RebateCash("0.8"); cs = cr2; break; } } public double GetResult(double money) { return cs.acceptCash(money); } } }