策略模式
策略模式主要解决枚举变化的情况,转化为一系列算法类。
enum TaxBase { CN_Tax, UR_Tax, UK_Tax, FR_Tax }; class SalesOrder { private: TaxBase tax; public: double CalculateTax() { if (tax == CN_Tax) { //... } else if(tax==UR_Tax){ //... } else if (tax == UK_Tax) { } } };
上述代码以汇率计算为例,可以看到,当要扩展另一个国家的汇率计算时,需要修改枚举和SalesOrder类,加上对应的else if,这样不利于扩展,可以将枚举定义成基类,如下代码所示:
#pragma once #ifndef STRATEGY_H #define STRATEGY_H #include<iostream> using namespace std; class TaxStrategy { public: virtual double CalculateTax(const double& money) = 0; virtual ~TaxStrategy() {} }; class CNTax :public TaxStrategy { public: double CalculateTax(const double& money) override{ cout << "Chinese money" << endl; return money; } }; class USTax :public TaxStrategy { public: double CalculateTax(const double& money) override { cout << "US money" << endl; return money; } }; class UKTax :public TaxStrategy { public: double CalculateTax(const double& money) override { cout << "UK money" << endl; return money; } }; #endif // !STRATEGY_H
strategy.h中,改变了枚举的类型,变成继承自抽象基类的子类。测试代码如下:
#include<iostream> using namespace std; #include"strategy.h" class SalesOrder { private: TaxStrategy* strategy; public: SalesOrder(TaxStrategy* strategy) {//若有多个策略,此处可以结合工厂模式 this->strategy = strategy; } ~SalesOrder() { delete this->strategy; } double Calculatetax() { double val = strategy->CalculateTax(10);//多态调用 cout << "success calculate" << endl; return val; } }; int main() { SalesOrder* sale = new SalesOrder(new USTax()); sale->Calculatetax(); return 0; }
通过这种方式,解决了上述扩展时,需要更改各种文件代码的问题,只需要添加扩展类即可,也无需修改SalesOrder 类的方法。
运行结果如下: