责任链模式 和 状态模式
共同点
核心逻辑, 都是在本类中, 包含另外一个能处理该逻辑的类, 如果本类无法处理, 就用另外一个类来处理
, 直至最终找到能够处理该逻辑的类,
不同点
有的说是责任链模式是客户端设置的下一级处理类, 状态模式是类中设置好的下个状态
其实根本逻辑都是差不多的, 只不过是下一级处理类的设置的阶段不通而已.

责任链模式

我们设置三个不同级别的身份
班长: 处理level <= 1的事务
教师: 处理level == 2的事务
校长: 处理所有级别的事务
然后在客户端( main方法里, 不是模式代码中 )分别设置他们的上一级处理人, 代码如下

class Processor
{
public:
	Processor* p;
	void set_superior(Processor* _p) { p = _p; }
	virtual void process(int level) = 0;
};


class Monitor : public Processor
{
public:
	void process(int level) override
	{
		if (level <= 1)
			cout << "monitor can process this" << endl;
		else
			p->process(level);
	}
};


class Teacher : public Processor
{
public:
	void process(int level) override
	{
		if (level <= 2)
			cout << "teacher can process this" << endl;
		else
			p->process(level);
	}
};


class Headmaster : public Processor
{
public:
	void process(int level) override
	{
		cout << "Headmaster process this" << endl;
	}
};


int main()
{
	Monitor* m = new Monitor();
	Teacher* t = new Teacher();
	Headmaster* h = new Headmaster();
	m->set_superior(t);
	t->set_superior(h);
	m->process(3);
	return 0;
}

执行结果
在这里插入图片描述

状态模式

状态模式的状态切换, 都是状态内部设置的, 客户端不用管
例如工作状态, 分为
早上: 10点前
中午: 13点前
下午: 18点前
晚上: 18点后
它们之间的状态切换会默认执行, 如下所示

class WorkState
{
public:
	virtual WorkState* work(int hour) = 0;
};



class NightState : public WorkState
{
public:
	WorkState* work(int hour) override
	{
		if (hour < 19)
		{
			cout << "time to dinner" << endl;
		}
		else
		{
			cout << "time to off work" << endl;
		}
		return this;
	}
};


class AfternoonState : public WorkState
{
public:
	WorkState* work(int hour) override
	{
		if (hour < 18)
		{
			cout << "afternoon time, good to work" << endl;
			return this;
		}
		else
		{
			WorkState* res = new NightState();
			res = res->work(hour);
			return res;
		}
	}
};


class NoonState : public WorkState
{
public:
	WorkState* work(int hour) override
	{
		if (hour < 13)
		{
			cout << "not time to noon sleep" << endl;
			return this;
		}
		else
		{
			WorkState* res = new AfternoonState();
			res = res->work(hour);
			return res;
		}
	}
};


class ForenoonState : public WorkState
{
public:
	WorkState* work(int hour) override
	{
		if (hour < 10)
		{
			cout << "not time to work" << endl;
			return this;
		}
		else if (hour < 12)
		{
			cout << "forenoon time to work" << endl;
			return this;
		}
		else
		{
			WorkState* res = new NoonState();
			res = res->work(hour);
			return res;
		}
	}
};



int main()
{
	WorkState* ws = new ForenoonState();

	ws = ws->work(7);
	ws = ws->work(11);
	ws = ws->work(12);
	ws = ws->work(15);
	ws = ws->work(19);

	return 0;
}

执行结果
在这里插入图片描述

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部