策略模式(反射)

本文介绍了一种使用反射改进的策略模式实现,并通过具体代码示例展示了如何根据不同折扣条件计算价格。该模式允许在运行时选择算法,提高了系统的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用反射改进后的策略模式

public abstract class CashSpuer
{
public abstract double acceptCash(double money);
}

public class CashNormal : CashSpuer
{
public override double acceptCash(double money)
{
return money;
}
}

public class CashRebate : CashSpuer
{
private double moneyRebate = 1d;
public CashRebate(string moneyRebate)
{
this.moneyRebate = double.Parse(moneyRebate);
}
public override double acceptCash(double money)
{
return money * moneyRebate;
}
}
public class CashReturn : CashSpuer
{
private double moneyCondition;
private double moneyReturn;
public CashReturn(string moneyCondition, string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}
public override double acceptCash(double money)
{
if (money > moneyCondition)
{
return money - Math.Floor(money / moneyCondition) * moneyReturn;
}
else
return money;
}
}

public class CashContext
{
private CashSpuer cs;
public void setBehavior(CashSpuer cs)
{
this.cs = cs;
}

public double acceptCash(double money)
{
return cs.acceptCash(money);
}
}
}

 

 

DataSet ds = null;
double total = 0d;
private void btnOK_Click(object sender, EventArgs e)
{
CashContext cc = new CashContext();
DataRow dr = ((DataRow[])ds.Tables[0].Select("name='" + cbxType.SelectedItem.ToString() + "'"))[0];
object[] args = null;
if (dr["para"].ToString().Trim() != "")
{
args = dr["para"].ToString().Split(',');
}

string strName = System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
cc.setBehavior((CashSpuer)Assembly.Load("WindowsFormsApplication2").CreateInstance("WindowsFormsApplication2." + dr["class"], false, BindingFlags.Default, null, args, null, null));
double totalPrice=0d;
totalPrice=cc.acceptCash(Convert.ToDouble(txtPrice.Text)*Convert.ToDouble(txtNums.Text));
total = total + totalPrice;
listBox1.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNums.Text + " " + cbxType.SelectedItem + " 合计:" + totalPrice.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
ds = new DataSet();
ds.ReadXml(Application.StartupPath + "\\CashAcceptType.xml");
foreach (DataRowView dr in ds.Tables[0].DefaultView)
{
cbxType.Items.Add(dr["name"].ToString());
}
cbxType.SelectedIndex = 0;
}

 

转载于:https://www.cnblogs.com/apple2017/p/8482846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值