大话设计模式之策略模式代码

本文通过具体的折扣计算案例,介绍了策略模式的设计思想及其实现方式。文章展示了如何使用策略模式来处理不同的收费策略,如正常收费、打折收费和返利收费等,并通过客户端代码演示了实际操作。

大话设计模式之策略模式代码:

//现金收费抽象类
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();
}
}
}

界面:

AS]7ZM{526UR]QM81PD~55F

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值