您的位置:首页 > 编程语言 > C#

C#学习笔记之 策略与简单工厂的结合

2018-02-26 09:27 549 查看
CashSuper类是抽象策略,CashNormal,CashRebate,CashReturn为三个具体的策略,策略无需改动,增加CashContext类,修改客户端代码即可namespace 商城收银管理
{//收费策略Context
class CashContext
{

private CashSuper cs;//声明一个现金收费父类对象

public CashContext(string type)//设置策略行为,参数具体的现金收费子类(正常,打折或返利)
{
switch (type)
{
case "正常收费":
cs = new cashNormal();
break;
case "满300返100":
cs= new CashReturn("300", "100");
break;
case "打8折":
cs = new CashRebate("0.8");
break;
}
}
//得到现金促销计算结果(利用了多台机制,不通的策略行为导致不同的结果)
public double GetResult(double money)
{
return cs.acceptCash(money);
}
}
}客户端代码
namespace 商城收银管理
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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();
}

private void btnClear_Click(object sender, EventArgs e)
{
total = 0;
txtPrice.Text = "1";
txtNum.Text = "0.00";
lbxList.Items.Clear();
lblResult.Text = "0.00";
}
}
}
CashSuper
namespace 商城收银管理
{
abstract class CashSuper
{
//抽象方法:收取现金,参数为原价,返回为当前价
public abstract double acceptCash(double money);
}
}
策略类
namespace 商城收银管理
{
class cashNormal:CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}
}

namespace 商城收银管理
{
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;
}
}
}

namespace 商城收银管理
{
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息