设计模式-状态模式

shienh 2020年01月27日 267次浏览

状态(State)模式的定义:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为

#include <iostream>
using namespace std;


class NetworkState{
public:
    NetworkState* pNext;
    virtual void Operation1()=0;
    virtual void Operation2()=0;
    ~NetworkState(){}
};

class OpenState:public NetworkState{
public:
    static NetworkState* getInstance(){
        if(instance == NULL){
            instance = new OpenState;
        }
        return instance;
    }

    void Operation1(){
        cout<<"OpenState Operation1"<<endl;
        pNext = OpenState::getInstance();
    }

    void Operation2(){
        cout<<"OpenState Operation2"<<endl;
        pNext = OpenState::getInstance();
    }
private:
    static NetworkState* instance;

};

NetworkState* OpenState::instance = NULL;

//增加状态只需要增加子类
class closeState:public NetworkState{
public:
    static NetworkState* getInstance(){
        if(instance == NULL){
            instance = new closeState;
        }
        return instance;
    }

    void Operation1(){
        cout<<"CloseState Operation1"<<endl;
        pNext = closeState::getInstance();
    }

    void Operation2(){
        cout<<"CloseState Operation2"<<endl;
        pNext = closeState::getInstance();
    }
private:
    static NetworkState* instance;

};

NetworkState* closeState::instance = NULL;

class NetworkProcessor{
public:
    NetworkProcessor(NetworkState* state){
        this->pState = state;
    }

    void operator1(){
        pState->Operation1();
        pState = pState->pNext;
    }

    void operator2(){
        pState->Operation2();
       // pState = pState->pNext;
    }
private:
    NetworkState* pState;
};

int main(int argc, char *argv[])
{
    NetworkState* state = OpenState::getInstance();
    NetworkProcessor* net = new NetworkProcessor(state);
    net->operator1();
    delete state;
    delete net;

    state = closeState::getInstance();
    net = new NetworkProcessor(state);
    net->operator1();
    delete state;
    delete net;
    return 0;
}