设计模式之简单模式与策略模式(二)
ebate = double.Parse(moneyRebate);
}
public override double acceptCash(double money)
{
return money * moneyRebate;
}
}
//返利收费子类
class CashReturn:CashSuper
{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn (string moneyCondition,string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}
public override double acceptCash(double money)
{
double result = money;
if (money >= moneyCondition)
result = money - Math.Floor(money / moneyCondition) * moneyReturn;
return result;
}
}
//现金收费工厂类
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 "打8折":
CashRebate cr2=new CashRebate ("0.8");
cs=cr2;
break ;
}
return cs ;
}
}
class CashContext
{
private CashSuper cs;//声明一个CashSuper对象;
public CashContext (CashSuper csuper)//通过构造方法,传入具体的收费策略;
{
this.cs=csuper ;
}
public double GetResult(double money)
{
return cs.acceptCash (money );//根据收费策略不同获得计算结果;
}
}
//客户端窗体程序
double total=0.0d;
private void bntOk_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 "打8折":
cc=new CashContext (new CashRebate ("0.8"));
break ;
}
CashSuper csuper = CashFactory.CreateCashAccept(cbxType.SelectedItem.ToString());
double totalPrices=0d;
//通过多态,可以得到收费的结果
totalPrices =csuper .acceptCash (Convert .ToDouble(txtPrice .Text)*Convert.ToDouble (txtNum.Text ) );
total=total+totalPrices;
lbxList .Items.Add("单价:"+txtPrice.Text +"数量:"+txtNum.Text +" "+cbxType.SelectedItem +"合计:" +totalPrices .ToString ());
lblResult.Text =total .ToString ();
}
}
}
大家通过这两段代码和我的描述应该对这两种模式有所了解了,理解的还不够深刻,希望大家多多指出!