策略模式是一種定義一系列演算法的方法,從概念上來看,所有這些演算法完成的都是相同的工作,只是實現不同,它可以以相同的方式呼叫所有的演算法,減少了各種演算法類與使用演算法類直接的耦合。
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(); }
介面截圖: