從《大話設計模式》這本書對策略模式的解析來看,策略模式的思想是:
【通過一個通用的上下文類Context,來儲存策略類對象,來提供統一的介面實現策略類的計算。】
這樣做的好處:
- 降低了前後端之間的耦合程度;
- 封裝了具體的演算法;
——什麼時候使用原則模式?【需要在不同時間應用不同的商務規則】
【上下文類】
class Context{public: Context(void); Context(Strategy* stra){this->strategy = stra;}; Context(const string &str); virtual ~Context(void); double ContextInterface(void); private: Strategy* strategy;};Context::Context(void){}Context::~Context(void){ if (this->strategy != NULL) { delete strategy; }}Context::Context(const string &str){ if (str == "StrategyOne") { this->strategy = new StrategyOne(); }else if (str == "StrategyTwo"){ this->strategy = new StrategyTwo(); }else{ assert(false); }}double Context::ContextInterface(void){ return this->strategy->AlgorithmInterface();}
【策略類】
class Strategy{public: Strategy(void); virtual ~Strategy(void); virtual double AlgorithmInterface(void) const = 0;};Strategy::Strategy(void){}Strategy::~Strategy(void){}
【策略子類One】
class StrategyOne : public Strategy{public: StrategyOne(void); virtual ~StrategyOne(void); virtual double AlgorithmInterface(void) const;};StrategyOne::StrategyOne(void){ }StrategyOne::~StrategyOne(void){ }double StrategyOne::AlgorithmInterface(void) const{ std::cout << "StrategyOne Called\n"; double result = 1; return result;}
【策略子類Two】
class StrategyTwo : public Strategy{public: StrategyTwo(void); virtual ~StrategyTwo(void); virtual double AlgorithmInterface(void) const;};StrategyTwo::StrategyTwo(void){ }StrategyTwo::~StrategyTwo(void){ }double StrategyTwo::AlgorithmInterface(void) const{ std::cout << "StrategyTwo Called\n"; double result = 2; return result;}
【main】
int main(int argc, const char * argv[]){ // insert code here... Context* context; context = new Context("StrategyTwo"); std::cout << context->ContextInterface() << endl; delete context; context = NULL; return 0;}
【結果】
StrategyTwo Called
2