设计模式的理会和实现(C++)之十七-State模式
副标题#e#
浸染:
答允一个工具在其内部状态改变时改变它的行为.
UML布局图:
理会:
State模式主要办理的是在开拓中时常碰着的按照差异的状态需要举办差异的处理惩罚操纵的问题,而这样的问题,大部门人是回收switch-case语句举办处理惩罚的,这样会造成一个问题:分支过多,并且假如插手一个新的状态就需要对本来的代码举办编译.State模式回收了对这些差异的状态举办封装的方法处理惩罚这类问题,当状态改变的时候举办处理惩罚然后再切换到另一种状态,也就是说把状态的切换责任交给了详细的状态类去认真.同时,State模式和Strategy模式在图示上有许多相似的处所,需要说明的是两者的思想都是一致的,只不外封装的对象差异:State模式封装的是差异的状态,而Stategy模式封装的是差异的算法.
实现:
1)State.h
/**//********************************************************************
created: 2006/08/05
filename: State.h
author: 李创
http://www.cppblog.com/converse/
purpose: State模式的演示代码
*********************************************************************/
#ifndef STATE_H
#define STATE_H
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);
};
#endif
#p#副标题#e#
2)State.cpp
/**//********************************************************************
created: 2006/08/05
filename: State.cpp
author: 李创
http://www.cppblog.com/converse/
purpose: State模式的演示代码
*********************************************************************/
#include "State.h"
#include <iostream>
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());
}
}
3)Main.cpp
/**//********************************************************************
created: 2006/08/05
filename: Main.cpp
author: 李创
http://www.cppblog.com/converse/
purpose: State模式的测试代码
*********************************************************************/
#include "State.h"
int main()
{
State *pState = new ConcreateStateA();
Context *pContext = new Context(pState);
pContext->Request();
pContext->Request();
pContext->Request();
delete pContext;
return 0;
}