Strategy
策略
定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换(变化)。该模式使得算法可以独立于使用它的客户程序(稳定)而变化(扩展、子类化)。
解决什么问题
在软件构建过程中,某些对象使用的算法可能多种多样,经常改变,如果将这些算法都编码到对象中,会使得对象变得异常复杂,而且有时候支持不使用的算法也是一个性能负担。
如何在运行时根据需求更透明的更改对象的算法?
将算法与对象本身解耦,从而避免上述问题?
要点总结
- Strategy及其子类为组件提供了一系列可重用的算法,从而使得类型在运行时方便的根据需要在各个算法之间切换
- Strategy提供了判断语句外的另一种选择
- 如果Strategy对象没有实例变量,那么各个上下文可以共享同一个Strategy对象,从而节省开销
没有使用策略模式:
// 结构化
// 为了区分每一种税收,必须为每一种税收分别做计算方法。
enum TaxBase { // 变化
CN_Tax,
US_Tax,
DE_Tax,
FR_Tax // 增加需求
};
class SalesOrder {
public:
// 这些方法,全部在类里面,虽然有枚举,可以跳过其他的方法,但这些方法的增删改都不方便,而且也会使得这个类很庞大
// 稳定
double CalculateTax() {
// ...
if (tax == CN_Tax) {
// ...
}
else if (tax == US_Tax) {
}
else if (tax == DE_Tax) {
}
else if (tax == FR_Tax) { // 增加 应该对扩展开放,对修改封闭
}
//...
}
private:
TaxBase tax;
};
使用策略模式:
// Strategy
class TaxStrategy {
public:
virtual double Calculate(const Context& context)=0;
virtual ~TaxStrategy(){}// 基类最好都实现一个虚的析构函数
};
// 变化
// 把每一种税收计算方法,都封装成一个类,这个类不能实例化,但却有重写的虚函数
// 这样,如果是增加或者减少方法,只需要增加或减少相应的类,而且,根据类不同,其他类的代码不会冗余进来
class CNTax : public TaxStratygy {
public:
virtual double Calculate(const Context& context) {
// ...
}
};
class USTax : public TaxStratygy {
public:
virtual double Calculate(const Context& context) {
// ...
}
};
class DETax : public TaxStratygy {
public:
virtual double Calculate(const Context& context) {
// ...
}
};
// 增加
class FRTax : public TaxStratygy {
public:
virtual double Calculate(const Context& context) {
// ...
}
};
// 稳定
class SalesOrder {
public:
SalesOrder(StrategyFactory* strategyFactory) {
this->strategy = strategyFactory->NewStrategy();
}
~SalesOrder() {
delete this->strategy;
}
double Calculate() {
// ...
Context context();
// 这个时候调用的就是实际的税收计算方法类里面的方法
double val = strategy->Calculate(contex);
// ...
}
private:
TaxStrategy* strategy;
};