1. 程式人生 > 實用技巧 >Design Patterns 4 - 策略模式 Strategy

Design Patterns 4 - 策略模式 Strategy

https://www.bilibili.com/video/BV1kW411P7KS?p=4

//strategy1.cpp

//變化:增加對法國的支援,違背開閉原則:對擴充套件開放,對更改封閉
enum TaxBase {
    CN_Tax,
    US_Tax,
    DE_Tax,
    FR_Tax //更改
};

class SalseOrder{
    TaxBase tax;
public:
    double CalculateTax(){
        //...
        
        if (tax == CN_Tax){ //一個個的演算法
            
//CN********** } else if (tax == US_Tax){ //US*********** } else if (tax == DE_Tax){ //DE*********** } else if (tax == FR_Tax){ //更改 //FR*********** } //.... } };

//strategy2.cp

//工程上,每個類單獨放一個檔案
class TaxStrategy{
public: virtual double Caculate(const Context &context) = 0; virtual ~TaxStrategy(){} }; //把一個個的演算法,變成了一個個子類 class CNTax : public TaxStrategy{ public: virtual double Caculate(const Context &context){ //************* } }; class USTax : public TaxStrategy{ public: virtual
double Caculate(const Context &context){ //************* } }; class DETax : public TaxStrategy{ public: virtual double Caculate(const Context &context){ //************* } }; //增加對法國的支援,增加一個子類,SalesOrder沒有任何改變,複用性強 //開放封閉原則 class FRTax : public TaxStrategy{ public: virtual double Caculate(const Context &context){ //.... } }; class SalesOrder{ private: TaxStrategy *strategy; //指標為變化帶來了可能 public: SalesOrder(StrategyFactory * strategyFactory){ this->strategy = strategyFactory->NewStrategy(); } ~SalesOrder(){} double CalculateTax(){ //... Context context(); double val = strategy->Calculate(context); //多型呼叫 //... } };