定义: 允许一个对象在其内部状态改变时改变它的行为
UML图:
代码实现:
class State
{
public:
virtual void Handle(Context *pContext) = 0;
};
class ConcreteStateA : public State
{
public:
virtual void Handle(Context *pContext)
{
std::cout << "test ConcreteStateA" << std::endl;
pContext->ChangeState(new ConcreteStateB);
}
};
class ConcreteStateB : public State
{
public:
virtual void Handle(Context *pContext)
{
std::cout << "test ConcreteStateB " << std::endl;
}
};
class Context
{
public:
Context(State *pState) : m_pState(pState){}
void Request()
{
if (m_pState)
{
m_pState->Handle(this);
}
}
void ChangeState(State *pState)
{
m_pState = pState;
}
private:
State *m_pState;
};
int main()
{
State *pStateA = new ConcreteStateA();
State *pStateB = new ConcreteStateB();
Context *pContext = new Context(pStateA);
pContext->Request();
pContext->ChangeState(pStateB);
pContext->Request();
}