策略模式:
与工厂不同的是,工厂是:
工厂类接受参数,实例化具体的类,返回类
策略模式是:
接受具体的实例化类,仅将方法赋予策略类
策略模式类:
class CashContext
{
private CashSuper cs;
public CashContext(CashSuper csuper)
{
this.cs = csuper;
}
public double GetResult(double monty)
{
return cs.acceptCash(monty);
}
}
抽象类和实现类:
abstract class CashSuper
{
public abstract double acceptCash(double money);
}
//正常收费
class CashNormal : CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}
//打折收费类
class CashRebhate : CashSuper
{
private double moneyRebate = 1d;
public CashRebhate(string moneyRebate)
{
this.moneyRebate = double.Parse(moneyRebate );
}
public override double acceptCash(double money)
{
return money * moneyRebate;
}
}
调用策略模式:
private voidbutton1_Click(object sender, EventArgs e)
{
CashContext cc =null;
switch (comboBox1.Text)
{
case "正常收费":
cc= new CashContext(new CashNormal());
break;
。。。。。。。。
}
double totals =Convert.ToDouble(textBox1.Text) * Convert.ToDouble(textBox2.Text);
totals =cc.GetResult(totals);