// State.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
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";
}
void ConcreateStateB::Handle(Context* pContext)
{
std::cout << "Handle by ConcreateStateB/n";
}
int _tmain(int argc, _TCHAR* argv[])
{
State *pStateA = new ConcreateStateA();
State *pStateB = new ConcreateStateB();
Context *pContext = new Context(pStateA);
pContext->Request();
cout<<"-------------------------------"<<endl;
pContext->ChangeState(pStateB);
pContext->Request();
delete pContext;
return 0;
}