#define _STATE_H_
class Context;
class State
{
public:
virtual void Handle(Context* pContext)=0;
~State();
protected:
State();
private:
};
class ConcreteStateA : public State
{
public:
ConcreteStateA();
~ConcreteStateA();
virtual void Handle(Context* pContext);
protected:
private:
};
class ConcreteStateB : public State
{
public:
ConcreteStateB();
~ConcreteStateB();
virtual void Handle(Context* pContext);
protected:
private:
};
class ConcreteStateC : public State
{
public:
ConcreteStateC();
~ConcreteStateC();
virtual void Handle(Context* pContext);
protected:
private:
};
class Context
{
public:
Context(State* pState);
~Context();
void Request();
void ChangeState(State* pState);
protected:
private:
State* _state;
};
#endif
#include "State.h"
#include <iostream>
using namespace std;
State::State()
{}
State::~State()
{}
ConcreteStateA::ConcreteStateA()
{}
ConcreteStateA::~ConcreteStateA()
{}
//执行该状态的行为并改变状态
void ConcreteStateA::Handle(Context* pContext)
{
cout << "ConcreteStateA" << endl;
pContext->ChangeState(new ConcreteStateB());
}
ConcreteStateB::ConcreteStateB()
{}
ConcreteStateB::~ConcreteStateB()
{}
//执行该状态的行为并改变状态
void ConcreteStateB::Handle(Context* pContext)
{
cout << "ConcreteStateB" << endl;
pContext->ChangeState(new ConcreteStateC());
}
ConcreteStateC::ConcreteStateC()
{}
ConcreteStateC::~ConcreteStateC()
{}
//执行该状态的行为并改变状态
void ConcreteStateC::Handle(Context* pContext)
{
cout << "ConcreteStateC" << endl;
pContext->ChangeState(new ConcreteStateA());
}
//定义_state的初始状态
Context::Context(State* pState)
{
this->_state = pState;
}
Context::~Context()
{}
//对请求做处理,并设置下一状态
void Context::Request()
{
if(NULL != this->_state)
{
this->_state->Handle(this);
}
}
//改变状态
void Context::ChangeState(State* pState)
{
this->_state = pState;
}
int main()
{
State* pState = new ConcreteStateA();
Context* pContext = new Context(pState);
pContext->Request();
pContext->Request();
pContext->Request();
pContext->Request();
pContext->Request();
return 0;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有