C++设计模式之二十:State(状态模式)

本文介绍了一种常用的设计模式——状态模式,通过该模式可以使对象根据内部状态的变化而改变其行为。文中详细解释了状态模式的基本概念,并提供了一个具体的实现案例,包括环境类、状态接口及具体状态子类的定义。

一、意图:

允许一个对象在其内部状态改变时改变它的行为。

二、类图:


三、组成元素:

                    i.           Context:环境

                  ii.           State:状态接口

ConcreteState:具体状态子类

四、实现代码:

#include "iostream"
using namespace std;

class Context;
class ConcreteStateA;
class ConcreteStateB;

class State
{
public:
	State()
	{

	}
	virtual void Handle(Context* pContext)=0;
};

class Context
{
private:
	State* m_State;
public:
	Context(State* pState)
	{
		m_State=pState;
	}
	void Request()
	{
		if (NULL!=m_State)
		{
			m_State->Handle(this);
		}
	}
	void ChangState(State* pState)
	{
		if (NULL!=m_State)
		{
			delete m_State;
			m_State=NULL;
		}
		m_State=pState;
	}
};


class ConcreteStateA:public State
{
public:
	ConcreteStateA()
	{

	}
	void Handle(Context* pContext)
	{
		cout<<"Handle by ConcreteStateA"<<endl;
		if (NULL!=pContext)
		{
			pContext->ChangState(new ConcreteStateB());
		}
	}
};


class ConcreteStateB:public State
{
public:
	ConcreteStateB()
	{

	}
	void Handle(Context* pContext)
	{
		cout<<"Handle by ConcreteStateB"<<endl;
		if (NULL!=pContext)
		{
			pContext->ChangState(new ConcreteStateA());
		}
	}
};

void main()
{
	State* pState=new ConcreteStateA();
	Context* pContext=new Context(pState);

	pContext->Request();
	pContext->Request();
	pContext->Request();

	delete pContext;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值