namespace 商城收银管理
{//收费策略Context
class CashContext
{
private CashSuper cs; //声明一个现金收费父类对象cs
//设置策略行为,参数具体的现金收费子类(正常,打折或返利)
public CashContext(CashSuper csuper)//通过策略方法,传入具体的收费策略
{
this.cs = csuper;
}
public double GetResult(double money)
{
return cs.acceptCash(money);//根据收费策略的不同,获得计算结果
}
}
}
客户端代码
namespace 商城收银管理
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double total = 0.0d;
private void btnOk_Click(object sender, EventArgs e)
{
CashContext cc= null;
switch (cbxType.SelectedItem.ToString())//根据希腊选择框,讲相应的策略对象作为参数传入CashContect对象中
{
case"正常收费":
cc = new CashContext(new cashNormal());
break;
case "满300返100":
cc = new CashContext(new CashReturn("300", "100"));
break;
case "打8折":
cc = new CashContext(new CashRebate("0.8"));
break;
}
double totalPrices = 0d;
totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text));//通过对Context的GetResult方法的调用,可以得到收取费用的结果,让具体算法与客户进行了隔离
total = total + totalPrices;
lbxList.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNum.Text + " " + cbxType.SelectedItem + " 合计:" + totalPrices.ToString());
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
total = 0;
txtPrice.Text = "1";
txtNum.Text = "0.00";
lbxList.Items.Clear();
lblResult.Text = "0.00";
}
}
}
其他算法类
namespace 商城收银管理
{
class cashNormal:CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}
}
namespace 商城收银管理
{
class CashRebate:CashSuper
{
private double moneyRebate = 1d;
public CashRebate(string moneyRebate)
{
this.moneyRebate = double.Parse(moneyRebate);
}
public override double acceptCash(double money)
{
return money * moneyRebate;
}
}
}