欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

State

程序员文章站 2024-03-13 16:26:57
...
#include <iostream>

using namespace std;

class Context;

class State{
public:
    virtual void doOperation(Context * context) = 0;
    virtual ~State(){}
};

class Context{
public:
    Context(State * state):m_state(state){}
    void Request(){
        if(nullptr != m_state)
        m_state->doOperation(this);
    }
    void changeState(State * state){ m_state = state; }
private:
    State * m_state;
};


class State1 : public State{
public:
    void doOperation(Context * context);
};

class State2 : public State{
public:
    void doOperation(Context * context);
};

class State3 : public State{
public:
    void doOperation(Context * context);
};

void State1::doOperation(Context *context)
{
    cout<<"State1 doOperation"<<endl;
    context->changeState(new State2);
}

void State2::doOperation(Context *context)
{
    cout<<"State2 doOperation"<<endl;
    context->changeState(new State3);
}

void State3::doOperation(Context *context)
{
    cout<<"State3 doOperation"<<endl;
    context->changeState(new State1);
}





int main()
{
    cout << "Hello World!" << endl;


    Context * context = new Context(new State1);
    context->Request();
    context->Request();
    context->Request();
    context->Request();
    context->Request();
    context->Request();
    context->Request();
    return 0;
}

 

相关标签: State 设计模式