策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类直接的耦合。
UML 图:
根据《大话设计模式》——第二章 商场促销这个案例代码来简单的记录一下策略模式的使用方式:
/// <summary> /// 现金收费抽象类 /// </summary> public abstract class CashSuper { /// <summary> /// 现金收取超类抽象方法收取现金 /// </summary> /// <param name="money">原价</param> /// <returns>当前价格</returns> public abstract double acceptCash(double money); }
/// <summary> /// 正常收费子类 /// </summary> public class CashNormal : CashSuper { public override double acceptCash(double money) { return money; } } /// <summary> /// 打折收费子类 /// </summary> public class CashRebate : CashSuper { private double moneyRebate = 1d; public CashRebate(string moneyRebate) { //打折收费,初始化时,必须需要输入折扣率,如八折就是 0.8 this.moneyRebate = double.Parse(moneyRebate); } public override double acceptCash(double money) { return money * moneyRebate; } } /// <summary> /// 返利收费子类 /// </summary> public class CashReturn : CashSuper { private double moneyCondition = 0.0d; private double moneyRetrun = 0.0d; public CashReturn(string moneyCondition,string moneyReturn) { //返利收费,初始化时候必须要输入返利条件和返利值,比如满 //300返回100,则moneyCondition为300,moneyReturn为100 this.moneyCondition = double.Parse(moneyCondition); this.moneyRetrun = double.Parse(moneyReturn); } public override double acceptCash(double money) { double result = money; if (money >=moneyCondition) { result = money - Math.Floor(money / moneyCondition) * moneyRetrun; } return result; } }
/// <summary> /// 上下文类 /// </summary> public class CashContext { CashSuper cs = null; public CashContext(string type) { switch (type) { case "正常收费": CashNormal cs0 = new CashNormal(); this.cs = cs0; break; case "满300返100": CashReturn cs1 = new CashReturn("300","100"); this.cs = cs1; break; case "打8折": CashRebate cs2 = new CashRebate("0.8"); this.cs = cs2; break; } } public double GetResult(double money) { return cs.acceptCash(money); } }
客户端代码:
void btnOk_Click(object sender, EventArgs e) { CashContext csuper = new CashContext(this.cbxType.Text); double totalPrices = 0d; totalPrices = csuper.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text)); total = total + totalPrices; lbxList.Items.Add("单价: " + txtPrice.Text + " 数量: " + txtNum.Text + " " + cbxType.Text + " 合计: " + totalPrices.ToString()); this.lblTotal.Text = total.ToString(); }
界面截图: