设计模式-状态模式

状态模式是一种行为设计模式,它使你能在运行时改变对象的行为。这种模式将与特定状态相关的行为局部化到一个独立的对象中,使得复杂的状态判断逻辑得以简化。
摘要由CSDN通过智能技术生成

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

#include <QCoreApplication>
#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[])
{
    QCoreApplication a(argc, 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 a.exec();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值