簡單工廠模式和策略模式的區別
阿新 • • 發佈:2018-11-25
首先看一下簡單工廠類和策略模式(Context)類中程式碼的區別:
簡單工廠類:
//現金收費工廠類 class CashFactory { public static CashSuper createCashAccept(string type) { CashSuper cs = null; switch (type ) { case "正常收費": cs = new CashNormal(); break; case "滿300返100": CashReturn cr1=new CashReturn ("300","100"); cs = cr1; break; case "打八折": CashRebate cr2 = new CashRebate("0.8"); cs = cr2; break; } return cs; } } //客戶端程式主要部分 double total = 0.0d; private void button1_Click(object sender, EventArgs e) { CashSuper csuper =CashFactory.createCashAccep(cbxType.SelectedItem.ToString()); double totalPrices = 0d; totalPrices= csuper.acceptCash(Convert.ToDouble(txtPrice.Text)*Convert.ToDoub(txtNum.Text); total = total + totalPrices; lbxList.Items.Add("單價:" + txtPrice.Text + "數量" + txtNum.Text + "合計:" + totalPrices.ToString()); lblResult.Text = total.ToString(); }
策略模式中Context 類:
class Context { CashSuper csuper; public Context(CashSuper cs) { this.csuper = cs; } public double GetResult(double money) { return csuper.acceptCash(money); } } //客戶端主要程式碼 double total =0.0d; private void btnOK_Click(object sender,EventArgs e) { CashContext cc=null; switch(cbxType.SelectedItem.Tostring()) { case"正常收費": cc=new CashContext(new CashNormal()); break; case"滿300返100": cc=new CashContext(new Cashreturn("300","100")); break; case"打7折": cc=new CashContext(new CashRebate("0.8")); break; } double totalPrices=0d; totalPrices=cc.GetResult(Convert.ToDouble(txtPrice.Text)*(Convert.ToDouble(txtNum.Text)); total = total + totalPrices; lbxList.Items.Add("單價:" + txtPrice.Text + "數量" + txtNum.Text + "" + cbxType.SelectedItem + "合計:" + totalPrices.ToString()); label5.Text = total.ToString(); }
從程式碼中可以看出:簡單工廠類中根據接收的條件建立一個相應的物件,而Context 類接收的是一個物件,然後執行該物件的方法。
簡單工廠模式和策略模式的區別:
簡單工廠模式:根據使用者選擇的條件,來幫使用者建立一個物件
策略模式:使用者首先建立好一個物件,根據物件來執行相應的方法。