panshiqu的专栏

给自己维护的项目打个广告:欢迎关注《休闲益智游戏》微信公众号

设计模式读书笔记:Decorator(装饰)

意图:

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

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


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

Component

namespace NS_DECORATOR {

class Component {
public:
	Component() {}
	virtual ~Component() {}
	virtual void operation(void) = 0;
};

} /* namespace NS_DECORATOR */
ConcreteComponent

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

namespace NS_DECORATOR {

class ConcreteComponent : public Component
{
public:
	ConcreteComponent() {}
	virtual ~ConcreteComponent() {}
	virtual void operation(void)
	{
		std::cout << "ConcreteComponent" << std::endl;
	}
};

} /* namespace NS_DECORATOR */
Decorator

#include "Component.h"

namespace NS_DECORATOR {

class Decorator : public Component
{
public:
	Decorator(Component *component) : _component(component) {}
	virtual ~Decorator() {}
	virtual void operation(void)
	{
		_component->operation();
	}

private:
	Component *_component;
};

} /* namespace NS_DECORATOR */
ConcreteDecoratorA

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

namespace NS_DECORATOR {

class ConcreteDecoratorA : public Decorator
{
public:
	ConcreteDecoratorA(Component *component) : Decorator(component) {}
	virtual ~ConcreteDecoratorA() {}
	virtual void operation(void)
	{
		Decorator::operation();
		addBehavior();
	}
	void addBehavior(void)
	{
		std::cout << "Jump" << std::endl;
	}
};

} /* namespace NS_DECORATOR */
ConcreteDecoratorB

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

namespace NS_DECORATOR {

class ConcreteDecoratorB : public Decorator
{
public:
	ConcreteDecoratorB(Component *component) : Decorator(component) {}
	virtual ~ConcreteDecoratorB() {}
	virtual void operation(void)
	{
		Decorator::operation();
		addBehavior();
	}
	void addBehavior(void)
	{
		std::cout << "Move" << std::endl;
	}
};

} /* namespace NS_DECORATOR */
main

#include "Decorator/ConcreteComponent.h"
#include "Decorator/ConcreteDecoratorA.h"
#include "Decorator/ConcreteDecoratorB.h"
using namespace NS_DECORATOR;
using namespace std;
int main(void)
{
	ConcreteComponent cc;
	cc.operation();

	cout << "----------" << endl;

	ConcreteDecoratorA cda(&cc);
	cda.operation();

	cout << "----------" << endl;

	ConcreteDecoratorB cdb(&cda);
	cdb.operation();
}
附加:
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/panshiqu/article/details/46832033
个人分类: 设计模式
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭