其他分享
首页 > 其他分享> > 状态模式

状态模式

作者:互联网

定义: 允许一个对象在其内部状态改变时改变它的行为
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();
}

标签:状态,pState,pContext,void,模式,State,Context,public
来源: https://blog.csdn.net/qqzhaojianbiao/article/details/116206352