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
下一篇: MySql 常用命令与配置