设计模式读书笔记: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();
}
附加:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值