定义:允许一个对象在其内部状态改变时改变它的行为。
组成
1) 使用环境(Context)角色:客户程序是通过它来满足自己的需求。它定义了客户程序
需要的接口;并且维护一个具体状态角色的实例,这个实例来决定当前的状态。
2) 状态(State)角色:定义一个接口以封装与使用环境角色的一个特定状态相关的行为。
3) 具体状态(Concrete State)角色:实现状态角色定义的接口。
类图如下,结构非常简单也与策略模式非常相似。
class State;
class Context
{
public:
Context(State* pState);
~Context();
void Request();
void ChangeState(State *pState);
private:
State *m_pState;
};
class State
{
public:
virtual ~State(){}
virtual void Handle(Context* pContext) = 0;
};
class ConcreateStateA
: public State
{
public:
void Handle(Context* pContext);
};
class ConcreateStateB
: public State
{
public:
void Handle(Context* pContext);
};
Context::Context(State* pState)
: m_pState(pState)
{
}
Context::~Context()
{
delete m_pState;
m_pState = NULL;
}
void Context::Request()
{
if (NULL != m_pState)
{
m_pState->Handle(this);
}
}
void Context::ChangeState(State *pState)
{
if (NULL != m_pState)
{
delete m_pState;
m_pState = NULL;
}
m_pState = pState;
}
void ConcreateStateA::Handle(Context* pContext)
{
std::cout << "Handle by ConcreateStateA\n";
if (NULL != pContext)
{
pContext->ChangeState(new ConcreateStateB());
}
}
void ConcreateStateB::Handle(Context* pContext)
{
std::cout << "Handle by ConcreateStateB\n";
if (NULL != pContext)
{
pContext->ChangeState(new ConcreateStateA());
}
}
int main()
{
State *pState = new ConcreateStateA();
Context *pContext = new Context(pState);
pContext->Request();
pContext->Request();
pContext->Request();
delete pContext;
return 0;
}