首页 > 代码库 > 设计模式C++实现——状态模式

设计模式C++实现——状态模式

模式定义

        状态模式同意对象在内部状态改变时改变它的行为,对象看起来好像改动了它的类。

模式结构:

技术分享

Context:

环境定义客户感兴趣的接口

维护一个ConcreteState子类的实例,这个实例定义当前状态

State:

定义一个接口封装与Context的一个特定状态相关的行为

ConcreteState subclasses:

每一子类实现一个与Context的一个状态相关的行为

举例:

        一个工人一天的时间分为上班,睡觉。干其它事情三个时间段。我们能够用状态模式来表示一天中在干什么事情。

UML设计:

 技术分享

编程实现及运行结果:

#include <iostream>
using namespace std;


class Worker;	//类的前置声明

//状态类
class State
{
public:
	virtual void doing(Worker* w){}
};
//工作状态
class WorkingState: public State
{
public:
	void doing(Worker* worker);
};
//歇息状态
class SleepingState: public State
{
public:
	void doing(Worker* worker);
};
//其它状态
class OtherState : public State
{
public:
	void doing(Worker* worker);
};

//工人类
class Worker
{
public:
	Worker()
	{
		state = new WorkingState();
	}
	void setState(State* stat)
	{
		state = stat;
	}
	double getHour()
	{
		return hour;
	}
	void setHour(double hou)
	{
		hour = hou;
	}

	void requestDoing()
	{
		state->doing(this);
	}
private:
	State* state;
	double hour;
};
//各个状态doing方法的实现
void WorkingState::doing(Worker* worker)
{
	if(worker->getHour() > 8 && worker->getHour()  < 16)
		cout << "WorkingState!" << endl;
	else
	{
		worker->setState(new OtherState());
		worker->requestDoing();
	}
}

void SleepingState::doing(Worker* worker)
{
	if(worker->getHour()  >= 21 || worker->getHour()  < 5)
		cout << "SleepingState!" << endl;
	else
	{
		worker->setState(new OtherState());
		worker->requestDoing();

	}
}

void OtherState::doing(Worker* worker)
{
	if((worker->getHour() >= 5 && worker->getHour() < 8) 
			|| (worker->getHour() >= 16 && worker->getHour() < 21))
		cout << "SleepingState!" << endl;
	else if(worker->getHour() >= 21 || worker->getHour() < 5)
	{
		worker->setState(new SleepingState());
		worker->requestDoing();
	}
	else
	{
		worker->setState(new WorkingState());
		worker->requestDoing();
	}
}
//客户代码
int main()
{
	Worker* pWorker = new Worker();
	pWorker->setHour(24);
	cout << "time 24" << endl;
	pWorker->requestDoing();

	pWorker->setHour(11.5);
	cout << "time 11.5" << endl;
	pWorker->requestDoing();

	pWorker->setHour(19);
	cout << "time 19" << endl;
	pWorker->requestDoing();
	
	delete pWorker;
	return 0;
}


运行结果:

time24

SleepingState!

time11.5

WorkingState!

time19

SleepingState!

请按随意键继续. . .

 

设计模式C++实现——状态模式