关闭

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

标签: 设计模式读书笔记Decorator装饰
252人阅读 评论(0) 收藏 举报
分类:

意图:

动态地给一个对象添加一些额外的职责。就增加功能来说,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();
}
附加:

0
0

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