大话设计模式之策略模式代码:
//现金收费抽象类
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 = 1;
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.0;
private double moneyReturn = 0.0;
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;
}
}
public class CashContext
{
CashSuper cs = null;
public CashContext(string type)
{
switch (type)
{
case "正常收费":
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case "满300返100":
CashReturn cs1 = new CashReturn("300", "100");
cs = cs1;
break;
case "打8折":
CashRebate cs2 = new CashRebate("0.8");
cs = cs2;
break;
}
}
public double GetResult(double money)
{
return cs.acceptCash(money);
}
}
}
客户端代码:
namespace 商场促销__策略模式
{
public partial class Frm1 : Form
{
public Frm1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lblResult.Text = "";
}
private void btnOk_Click(object sender, EventArgs e)
{
//判断各项是否为空
if (Convert.ToString(txtPrice.Text) == "")
{
MessageBox.Show("请输入单价!", "提示");
}
double total = 0.0;
CashContext csuper = new CashContext(cbxType.SelectedItem.ToString());
double totalPrices = 0;
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();
}
private void btnReSet_Click(object sender, EventArgs e)
{
txtPrice.Text = "";
txtNum.Text = "";
cbxType.Text = "";
lbxList.Items.Clear();
lblResult.Text = "";
txtPrice.Focus();
}
}
}
界面: