C++ 状态模式解析

1,830 阅读1分钟

C++ 状态模式解析

状态模式定义

  • 状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类

状态模式实例

以红绿灯为例

参考:blog.csdn.net/liang198908…

头文件:

#include "stdafx.h"

using namespace std;

//信号灯状态类
class IState
{
public:
	virtual void Handle() = 0;
};


//交通信号灯类
class TrafficLights
{
public:
	TrafficLights();
	void SetState(IState* cur_state); //设置状态
	void Request();

private:
	IState * m_pState;
};

//红绿灯类
//红灯
class RedLight:public IState
{
public:
	RedLight(TrafficLights* context);
    virtual void Handle();
private:
	TrafficLights* m_pContext;
};

//绿灯
class GreenLight:public IState
{
public:
	GreenLight(TrafficLights* context);
	virtual void Handle() ;
private:
	TrafficLights* m_pContext;
};

//黄灯
class YellowLight:public IState
{
public:
	YellowLight(TrafficLights* context);
	virtual void Handle() ;
private:
	TrafficLights* m_pContext;
};

实现文件cpp

// MoodMode.cpp : 定义控制台应用程序的入口点。
// 状态模式实例

#include "stdafx.h"
#include "MoodMode.h"

using namespace std;

//具体实现cpp
//交通信号灯
TrafficLights::TrafficLights()
{
	m_pState = new RedLight(this);
}

void TrafficLights::SetState(IState* cur_state)
{
	m_pState = cur_state; 
}

void TrafficLights::Request()
{
	m_pState->Handle();
}

//红灯
RedLight::RedLight(TrafficLights* context)
{
	m_pContext=context;
}

void RedLight::Handle()
{
	std::cout << "RedLight" << endl;
	m_pContext->SetState(new GreenLight(m_pContext));
	delete this;
}

//绿灯
GreenLight::GreenLight(TrafficLights* context)
{
	m_pContext=context;
}

void GreenLight::Handle()
{
	std::cout << "GreenLight" << endl;
	m_pContext->SetState(new YellowLight(m_pContext));
	delete this;
}

//黄灯
YellowLight::YellowLight(TrafficLights* context)
{
	m_pContext=context;
}

void YellowLight::Handle()
{
	std::cout << "YellowLight" << endl;
	m_pContext->SetState(new RedLight(m_pContext));
	delete this;
}

int _tmain(int argc, _TCHAR* argv[])
{
	TrafficLights tl;

	enum TLState {Red, Green, Yellow};

	TLState state = Red;  // 初始状态为红灯
	int i = 0;  // 总次数
	int seconds;  // 秒数

	while (true) {
		// 表示一个完整的状态流(红灯->绿灯->黄灯)已经完成
		if (i % 3 == 0)
			std::cout << "**********" << "Session " << ((i+1)/3)+1 << "**********" << std::endl;

		// 根据当前状态来设置持续时间,红灯(6秒)、绿灯(4秒)、黄灯(2秒)
		if (state == Red) {
			seconds = 6;
			state = Green;
		} else if (state == Green) {
			seconds = 4;
			state = Yellow;
		} else if (state == Yellow) {
			seconds = 2;
			state = Red;
		}

		// 休眠
		Sleep(seconds * 1000);

		tl.Request();
		i++;
	}

	system("pause");
	return 0;
}


运行结果: