策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
UML图如下:
Strategy是一个抽象类,其中有一个抽象方法Algorithmlnterface(),继承Stratety抽象类的就是具体的算法类,而重写基类的AlgorithmInterface()方法,返回具体算法的返回值。例如:一个商场收银的举例《大话设计模式》
public abstract class AlgrithmSuper { public abstract double AlgrithmResult(double money); }
/// <summary> /// 按折扣打折 /// </summary> public class AlgrithmA:AlgrithmSuper { private double MoneyRebate = 1; public AlgrithmA(string moneyRebate) { this.MoneyRebate = double.Parse(moneyRebate); } public override double AlgrithmResult(double money) { return money * this.MoneyRebate; } }
/// <summary> /// 满300减100 /// </summary> public class AlgrithmB:AlgrithmSuper { private double LimitMoney; private double PlusMoney; public AlgrithmB(double limitmoney,double pluemoney) { this.LimitMoney = limitmoney; this.PlusMoney = pluemoney; } public override double AlgrithmResult(double money) { return money > LimitMoney ? money - this.PlusMoney : money; } }
/// <summary> /// 原价 /// </summary> public class AlgrithmC:AlgrithmSuper { public AlgrithmC() { } public override double AlgrithmResult(double money) { return money; } }
==上述的AlgrithmSuper抽象类中有一个抽象方法就是用来计算并返回实际该收的钱,而继承它的三个类AlgrithmA、AlgrithmB、AlgrithmC就是三个算法分别实现了打折、满xx返xx、原价。
由上述的类,我们现在可以这样调用:
AlgrithmSuper algrithm=new AlgrithmA(0.80) double result= algrithm.AlgrithmResult(1000);
而策略模式,则用一个策略上下文,维护一个对 策略(Strategy,AlgrithmSuper) 对象的引用,即:
public class StrategyContext { private AlgrithmSuper Algrithm = null; public StrategyContext(AlgrithmSuper algrithm) { this.Algrithm = algrithm; } public double GetResult(double money) { return Algrithm.AlgrithmResult(money); } }
调用时:
StrategyContext context=new StrategyContext(new AlgrithmA(0.80));
context.GetResult(1000);
至此,对于策略模式中通过基类抽象类对各个实际算法的封装,并通过一个策略上下文实现依赖注入。