C++:策略模式

策略模式:

定義一系列的算法,將它們封裝起來。並且使他們互相可以替換,該模式可以使算法獨立於他的客戶而實現。

就像工資,不同的工作工資的算法不同,我們不能對工資算法硬性編碼,應該是可以自由變化的,

在這裏插入圖片描述
Strategy:定義所有支持的算法的公共接口。Context使用這個接口來調用某ConcreteStrategy定義的算法;
ConcreteStrategy:實現Strategy接口的具體算法;
Context:使用一個ConcreteStrategy對象來配置;維護一個對Stategy對象的引用,同時,可以定義一個接口來讓Stategy訪問它的數據。

使用場合

當存在以下情況時使用Strategy模式:

許多相關的類僅僅是行爲有異。“策略”提供了一種用多個行爲中的一個行爲來配置一個類的方法;
需要使用一個算法的不同變體;
算法使用客戶不應該知道的數據。可使用策略模式以避免暴露覆雜的、與算法相關的數據結構;
一個類定義了多種行爲,並且這些行爲在這個類的操作中以多個條件語句的形式出現。將相關的條件分支移入它們各自的Strategy類中以替代這些條件語句。



#include<iostream>
using namespace std;

class Strategy{
public :
    virtual void AlgorithmInterface() = 0;
};

class StrategyA : public Strategy{
public :
    void AlgorithmInterface(){
        cout<<"我來自策略模式A"<<endl;
    }
};

class StrategyB : public Strategy{
public :
    void AlgorithmInterface(){
        cout<<"我來自策略模式B"<<endl;
    }
};

class StrategyC :public Strategy{
public :
    void AlgorithmInterface(){
        cout<<"我來自策略模式C"<<endl;
    }
};
class Context{
public:
    Context(Strategy *pStrategy ):pStrategy(pStrategy){}
    void ContextInterface(){
        pStrategy->AlgorithmInterface();
    }
private :
    Strategy *pStrategy;
};

int main(){
    Strategy *pstrategyA = new StrategyA();
    Strategy *pstrategyB = new StrategyB();
    Strategy *pstrategyC = new StrategyC();
    Context *pcontextA = new Context(pstrategyA);
    Context *pcontextB = new Context(pstrategyB);
    Context *pcontextC = new Context(pstrategyC);
    pcontextA->ContextInterface();
    pcontextB->ContextInterface();
    pcontextC->ContextInterface();
    if(pstrategyA)delete pstrategyA;
    if(pstrategyB)delete pstrategyB;
    if(pstrategyC)delete pstrategyC;
    if(pcontextA)delete pcontextA;
    if(pcontextB)delete pcontextB;
    if(pcontextC)delete pcontextC;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章