乐趣区

状态模式

简介

状态模式,指当一个对象的内部状态发生改变时,允许改变它的行为。

UML 类图

示例

这里我们使用播放器的播放和停止两个状态来模拟状态模式,如下:
状态类,state.h

#ifndef STATE_H
#define STATE_H
#include <iostream>

using namespace std;
#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
class CPlayerContext;
class CState
{
public:
    virtual void Switch(CPlayerContext* pContext) = 0;
};

class CPlayState:public CState
{
public:
    void Switch(CPlayerContext* pContext);
};

class CStopState:public CState
{
public:
    void Switch(CPlayerContext* pContext);
};

class CPlayerContext
{
public:
    void Request();
    CState* GetState()
    {return m_pState;}
    void SetState(CState* pState)
    {m_pState = pState;}
private:
    CState* m_pState;
};
#endif

状态类实现,state.cpp

#include "state.h"

void CPlayState::Switch(CPlayerContext* pContext)
{CState* pState = pContext->GetState();
    SAFE_DELETE(pState);
    cout<<"Play->Stop"<<endl;
    pContext->SetState(new CStopState);
}

void CStopState::Switch(CPlayerContext* pContext)
{CState* pState = pContext->GetState();
    SAFE_DELETE(pState);
    cout<<"Stop->Play"<<endl;
    pContext->SetState(new CPlayState);
}

void CPlayerContext::Request()
{m_pState->Switch(this);
}

客户端调用,main.cpp

#include "state.h"

int main(int argc, char* argv[])
{
    CPlayerContext* pContext = new CPlayerContext;
    CState* pState = new CStopState;
    pContext->SetState(pState);
    pContext->Request();
    pContext->Request();
    SAFE_DELETE(pState);
    SAFE_DELETE(pContext);
    return 0;
}

输出如下:

Stop->Play
Play->Stop
退出移动版