策略模式:它定義了算法家族,分別封裝起來,讓它們之間能夠相互替換,此模式讓算法的變化,不會影響到使用算法的客戶。算法
今天來經過一個案例,來說一下商場的促銷案例。通常商場會有那些活動呢?總結了下,通常會有這3種促銷活動:一、正常收費;二、打折;三、滿多少返多少編程
面向對象的編程,並非類越多越好,類的劃分是爲了封裝,但分類的基礎是抽象,具備相同屬性和功能的抽象集合纔是類。ide
現金收費抽象類:this
1 abstract class CashSupper //現金收費抽象類 2 { 3 public abstract double acceptCash(double money);//現金收取類的抽象方法,收取現金,參數爲原價,返回爲當前價 4 }
正常收費子類:spa
1 class CashNormal : CashSupper //正常收費子類 2 { 3 public override double acceptCash(double money) 4 { 5 return money; 6 } 7 }
打折收費子類:code
1 class CashRebate : CashSupper //打折收費子類 2 { 3 private double moneryRebate = 1d; 4 public CashRebate(string moneryRebate) 5 { 6 this.moneryRebate = double.Parse(moneryRebate); //打折收費,初始化時,必需要輸入折扣率,如八折,就是0.8 7 } 8 public override double acceptCash(double money) 9 { 10 return money * moneryRebate; 11 } 12 }
返利收費子類:orm
1 class CashReturn : CashSupper 2 { 3 private double moneryCondition = 0.0d; 4 private double MoneryReturn = 0.0d; 5 public CashReturn(string moneryCondition,string moneryReturn) //返利收費,初始化時必需要輸入返利條件和返利值,好比滿300返100,則moneryCondition=300,moneryReturn=100 6 { 7 this.moneryCondition =double.Parse(moneryCondition); 8 this.MoneryReturn = double.Parse(moneryReturn); 9 } 10 public override double acceptCash(double money) 11 { 12 double result = money; 13 if (money>=moneryCondition) //若大於返利條件,則須要減去返利值 14 { 15 result = money - Math.Floor(money / moneryCondition) * MoneryReturn; 16 } 17 return result; 18 } 19 }
現金收費工廠類:對象
1 class CashFactory 2 { 3 public static CashSupper createCashAccept(string type) 4 { 5 CashSupper cs = null; 6 switch (type) 7 { 8 case "正常收費": 9 cs = new CashNormal(); 10 break; 11 case "滿300反100": 12 CashReturn cr1 = new CashReturn("300","100"); 13 cs = cr1; 14 break; 15 case "打8折": 16 CashRebate cr2 = new CashRebate("0.8"); 17 cs = cr2; 18 break; 19 } 20 return cs; 21 } 22 }
CashContext類:blog
1 class CashContext 2 { 3 private CashSupper cs=null; //聲明一個CashSuper 4 public CashContext(string type) //表示收費的類型 5 { 6 switch (type) 7 { 8 case "正常收費": 9 CashNormal cs0 = new CashNormal(); 10 cs = cs0; 11 break; 12 case "滿300返100": 13 CashReturn cr1 = new CashReturn("300","100"); 14 cs = cr1; 15 break; 16 case "打8折": 17 CashRebate cr2 = new CashRebate("0.8"); //將實例化具體策略的過程由客戶端轉移到Context類中。簡單工廠的引用 18 cs = cr2; 19 break; 20 } 21 } 22 public double GetResult(double Money) 23 { 24 return cs.acceptCash(Money); //根據收費策略的不一樣,得到計算結果 25 } 26 }
界面:string
調用:
1 double total = 0.0d; //用戶總計 2 private void btnOk_Click(object sender, EventArgs e) 3 { 4 CashContext cc = new CashContext(cmbType.SelectedItem.ToString()); 5 double totalPrices = 0d; 6 totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text)*Convert.ToDouble(txtNumber.Text)); //經過對Context的GetResult方法的調用,能夠獲得收取費用的結果,讓具體算法與客戶進行隔離 7 total = total + totalPrices; 8 listBox1.Items.Add("單價:"+txtPrice.Text+"數量:"+txtNumber.Text+" "+cmbType.SelectedItem+"合計:"+totalPrices.ToString()); 9 label5.Text = total.ToString(); 10 }