首先看一下简单工厂类和策略模式(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 类接收的是一个对象,然后执行该对象的方法。
简单工厂模式和策略模式的区别:
简单工厂模式:根据用户选择的条件,来帮用户创建一个对象
策略模式:用户首先创建好一个对象,根据对象来执行相应的方法。