状态模式

定义: 允许一个对象在其内部状态改变时改变它的行为
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();
}
上一篇:如何将mfcc向量与注释中的标签组合以传递给神经网络


下一篇:MFCC语音处理的简要流程