策略模式(反射)

2018-03-01 07:50:57来源:cnblogs.com作者:apple201703人点击

分享

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

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;
}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台