根据不同的情况使用不同的策略
简单一点:
class Context
public abstract class CashSuper
public abstract double One(double a);
class A : CashSuper
class B : CashSuper
class C : CashSuper
A,B,C分别为3个不同的策略
并重写父类中的One方法
Context中,则控制使用那种策略
在初始化构造函数的时候,将策略传入
3中策略我们不知道传哪一种,则想到可以传递父类
在Context中再添加一个方法,执行策略即可
例子:商场促销,根据不同的促销模式使用不同的策略,如:打8折,满200返40等
代码:
1 public abstract class CashSuper 2 { 3 public abstract double CashOne(double money); 4 } 5 /// <summary> 6 /// 正常收费 7 /// </summary> 8 public class CashA : CashSuper 9 { 10 public override double CashOne(double money) 11 { 12 return money; 13 } 14 } 15 /// <summary> 16 /// 打8折 17 /// </summary> 18 public class CashB : CashSuper 19 { 20 double moneyB = 1d; 21 public CashB(string moneyB) 22 { 23 this.moneyB = Convert.ToDouble(moneyB); 24 } 25 public override double CashOne(double money) 26 { 27 return money * moneyB; 28 } 29 } 30 31 /// <summary> 32 /// 满200返40 33 /// </summary> 34 public class CashC : CashSuper 35 { 36 double moneyCondition = 0d; 37 double moneyReturn = 0d; 38 public CashC(string moneyCondition,string moneyReturn) 39 { 40 this.moneyCondition = Convert.ToDouble( moneyCondition); 41 this.moneyReturn = Convert.ToDouble(moneyReturn); 42 } 43 44 public override double CashOne(double money) 45 { 46 double result = money; 47 if (money >= moneyCondition) 48 { 49 result = result - Math.Floor(moneyCondition / money) * moneyReturn; 50 } 51 return result; 52 } 53 }
1 public class CashContext 2 { 3 CashSuper c = null; 4 public CashContext(CashSuper c) 5 { 6 this.c = c; 7 } 8 9 public double GetResult(double money) 10 { 11 return c.CashOne(money); 12 } 13 }
来自:大话设计模式