分析详见:http://lvxingzhelimin.blog.163.com/blog/static/170716550201110991449718/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//设定金额默认值,提高程序健壮性,全局变量
double total = 0.0d;
private void btnOk_Click(object sender, EventArgs e)
{
//根据下列选择框,将相应的算法类型字符串传入CashContext的对象中
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 btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
//简单工厂和策略模式的结合:将选择判断封装分离客户端,通过字符串变量来实现。
class CashContext
{
//默认计算方法为空
CashSuper cs = null;
//通过利用简单工厂思想,将实例化具体策略的过程由客户端转移到此类中,
//也正是因为利用了简单工厂,这里传入的不是具体的对象,而是一个字符串,表示收费类型。
public CashContext(string type)
{
switch (type)
{
case "正常收费":
CashNomal cs0 = new CashNomal();
cs = cs0;
break;
case "打折收费":
CashRebate cr1 = new CashRebate("0.8");
cs = cr1;
break;
case "满300返100":
CashReturn cr2 = new CashReturn ("300","100");
cs = cr2;
break ;
}
}
//通过此方法计算实际金额,并显示出来。
public double GetResult(double money)
{
return cs.acceptCash(money );
}
}
//定义算法的公共接口
abstract class CashSuper
{
public abstract double acceptCash(double money);
}
//定义具体算法子类
//正常收费子类
class CashNomal : CashSuper
{
public override double acceptCash(double money)
{
return money;
}
}
//打折收费子类
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;
}
}
//返利收费子类
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;
}
}