一、做一个商场收银软件
二、Code
using System; namespace Web.策略模式 { /// <summary> /// 现金收费抽象类 /// </summary> public abstract class CashSuper { /// <summary> /// 现金收取超类的抽象方法,收取现金,参数为原价,返回当前价 /// </summary> /// <param name="money"></param> /// <returns></returns> public abstract double AcceptCash(double money); } /// <summary> /// 正常收费子类 /// </summary> class CashNoraml:CashSuper { /// <summary> /// 正常收费 返回价格 /// </summary> /// <param name="money"></param> /// <returns></returns> public override double AcceptCash(double money) { return money; } } /// <summary> /// 打折收费子类 /// </summary> public class CashRebate : CashSuper { private double moneyRebate = 1d; public CashRebate(string moneyRebate) { this.moneyRebate = double.Parse(moneyRebate); } /// <summary> /// 返回折扣价格×原价 /// </summary> /// <param name="money"></param> /// <returns></returns> public override double AcceptCash(double money) { return money*moneyRebate; } } /// <summary> /// 返利收费子类 /// </summary> public class CashReturn : CashSuper { private double moneyCondition = 0.0d; private double moneyRetrun = 0.0d; /// <summary> /// 返利收费, /// 初始化时必须要输入返利条件和返回值,比如满300返100,则moneyCondition为300,momeyReturn为100 /// </summary> /// <param name="moneyCondition"></param> /// <param name="moneyReturn"></param> public CashReturn(string moneyCondition, string moneyReturn) { this.moneyCondition =double.Parse(moneyCondition) ; this.moneyRetrun =double.Parse(moneyReturn) ; } /// <summary> ///若大于返利条件则需要减去返利值 /// </summary> /// <param name="money"></param> /// <returns></returns> public override double AcceptCash(double money) { double result = money; if (money>moneyCondition) { result = money - Math.Floor(money/moneyCondition)*moneyRetrun; } return result; } } /// <summary> /// 现金收费工厂类 /// </summary> public class CashFactory { public static CashSuper CreateCashSuper(string type) { CashSuper cash = null; switch (type) { case "正常收费": cash=new CashNoraml(); break; case "满300返100": cash =new CashReturn("300","100"); break; case "打折:85折": cash=new CashRebate("0.85"); break; } return cash; } } /// <summary> /// 客户端实现 /// </summary> class Customer { public void Method() { CashSuper cash = CashFactory.CreateCashSuper("type"); cash.AcceptCash(100); } } }
三、UML类图一些概念
如果商场现在需要买100送10元 消费100送10个积分 怎么办? 策略模式登场
《大话设计模式》