行为型模式之状态模式

#include<iostream>
using namespace std;

class Worker;

class State
{
public:
	virtual void doSomething(Worker*worker) = 0;
};

class Worker
{
public:
	Worker();
	void setHour(int hour)
	{
		m_hour = hour;
	}

	int getHour()
	{
		return m_hour;
	}

	void setState(State*state)
	{
		m_state = state;
	}

	State *getState()
	{
		return m_state;
	}
private:
	int m_hour;
	State *m_state;
};

class State1 :public State
{
public:
	virtual void doSomething(Worker*worker);
};

class State2 :public State
{
public:
	virtual void doSomething(Worker*worker);
};

void State1::doSomething(Worker*worker)
{
	if (worker->getHour() == 7 || worker->getHour() == 8)
	{
		cout << "吃早饭!" << endl;
	}
	else
	{
		delete worker->getState();//状态转换,先清空当前状态
		worker->setState(new State2);//然后转换到下一个状态
		worker->getState()->doSomething(worker);//执行下一个状态的行为
	}
}

void State2::doSomething(Worker*worker)
{
	if (worker->getHour() == 9 || worker->getHour() == 10)
	{
		cout << "工作!" << endl;
	}
	else
	{
		delete worker->getState();
		worker->setState(new State1);
		cout << worker->getHour() << "点,未知" << endl;
	}
}

Worker::Worker()
{
	m_state = new State1;
}
void main()
{
	State *state1 = new State1;
	State *state2 = new State2;

	Worker *worker1 = new Worker;

	worker1->setHour(7);
	state1->doSomething(worker1);

	worker1->setHour(10);
	state1->doSomething(worker1);

	worker1->setHour(15);
	state1->doSomething(worker1);
}

运行结果:


阅读更多
上一篇行为型模式之访问者模式
下一篇行为型模式之解释器模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭