Java教程

状态模式

本文主要是介绍状态模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定义: 允许一个对象在其内部状态改变时改变它的行为
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();
}
这篇关于状态模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!