《大話設計模式》之 第2章 商場促銷——策略模式 小結

來源:互聯網
上載者:User

從《大話設計模式》這本書對策略模式的解析來看,策略模式的思想是:

【通過一個通用的上下文類Context,來儲存策略類對象,來提供統一的介面實現策略類的計算。】

這樣做的好處:

  1. 降低了前後端之間的耦合程度;
  2. 封裝了具體的演算法;

——什麼時候使用原則模式?【需要在不同時間應用不同的商務規則】

【上下文類】

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.