策略模式(Strategy)
它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
感觉策略模式和工厂模式的思想是类似的,工厂模式把在不同情况下创建对象的步骤抽象成类,策略模式把不同的算法实现抽象出来,策略类似一个管理算法的工厂。
简单工厂模式与策略模式
现金收费抽象类:
abstract class CashSuper
{
public abstract double acceptCash(double money);
}
正常收费子类:
class CashNormal : CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}
打折收费子类:
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;
}
}
返利收费子类:
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;
}
}
CashContext类:
class CashContext
{
CashSuper cs = null;
public CashContext(string type)
{
//策略与简单工厂的结合
swich(type)
{
case "正常收费":
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case "满300返100":
CashReturn cr1 = new CashReturn("300", "100");
cs = cr1;
break;
case "打8折":
CashRebate cr2 = new CashRebate("0.8");
cs = cr2;
break;
}
}
public double GetResult(double money)
{
return cs.acceptCash(money);
}
}
客户端代码:
//客户端窗体程序(主要部分)
double total = 0.0d;
private void btnOk_Click(object sender, EventArgs e)
{
CashContext csuper = new CashContext(cbxType.SelectedItem.ToString());
double totalPrices = 0d;
totalPrices = csuper.GetResult(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();
}