关闭

设计模式读书笔记:State(状态)

标签: 设计模式读书笔记State状态
288人阅读 评论(0) 收藏 举报
分类:

意图:

允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

结构图:来自 《23种设计模式 - 郗晓勇》


实现:https://github.com/panshiqu/patterns/tree/master/State

Context

namespace NS_STATE {

class State;
class Context {
public:
	Context(State *state) : _state(state) {}
	virtual ~Context() {}
	void request(void);

private:
	friend class State;
	void changeState(State *state);

private:
	State *_state;
};

} /* namespace NS_STATE */
#include "Context.h"
#include "State.h"

namespace NS_STATE {

void Context::request(void)
{
	_state->handle(this);
}

void Context::changeState(State *state)
{
	_state = state;
}

} /* namespace NS_STATE */

State

#include "Context.h"

namespace NS_STATE {

class State {
public:
	State() {}
	virtual ~State() {}
	virtual void handle(Context *context) = 0;

protected:
	void changeState(Context *context, State *state)
	{
		context->changeState(state);
	}
};

} /* namespace NS_STATE */

ConcreteStateA

#include "State.h"
#include "ConcreteStateB.h"
#include <iostream>

namespace NS_STATE {

class ConcreteStateA : public State
{
public:
	ConcreteStateA() {}
	virtual ~ConcreteStateA() {}
	virtual void handle(Context *context)
	{
		std::cout << "ConcreteStateA." << std::endl;
		changeState(context, ConcreteStateB::getInstance());
	}
};

} /* namespace NS_STATE */
ConcreteStateB

#include "State.h"
#include <iostream>

namespace NS_STATE {

class ConcreteStateB : public State
{
public:
	ConcreteStateB() {}
	virtual ~ConcreteStateB() {}
	static ConcreteStateB *getInstance(void)
	{
		static ConcreteStateB instance;
		return &instance;
	}
	virtual void handle(Context *context)
	{
		std::cout << "ConcreteStateB." << std::endl;
	}
};

} /* namespace NS_STATE */
main

#include "State/Context.h"
#include "State/ConcreteStateA.h"
#include "State/ConcreteStateB.h"
using namespace NS_STATE;
int main(void)
{
	ConcreteStateA csa;
	Context c(&csa);
	c.request();
	c.request();
}
附加:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:78373次
    • 积分:1282
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:0篇
    • 译文:0篇
    • 评论:38条
    文章分类
    最新评论