C++设计模式-装饰器(Decorator)

目录

C++设计模式-装饰器(Decorator)

一、意图

二、适用性

三、结构

四、参与者

五、代码


C++设计模式-装饰器(Decorator)

一、意图

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

二、适用性

  • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  • 处理那些可以撤消的职责。
  • 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

三、结构

 

四、参与者

  • Component

        定义一个对象接口,可以给这些对象动态地添加职责。

  • ConcreteDecorator

       定义一个对象,可以给这个对象添加一些职责。

  • Decorator

        维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。

  • ConcreteComponent

        向组件添加职责。

五、代码

#include<iostream>
using namespace std;

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

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

class Decorator : public Component {
public:
	Decorator(Component* tempComponent) :component(tempComponent) {}
	virtual void Operation() {
		component->Operation();
	}
private:
	Component* component;
};

class ConcreteDecoratorA : public Decorator {
public:
	ConcreteDecoratorA(Component* tempComponent) :Decorator(tempComponent) {}
	virtual void Operation() {
		Decorator::Operation();
		cout << "ConcreteDecoratorA" << endl;
	}
};

class ConcreteDecoratorB : public Decorator {
public:
	ConcreteDecoratorB(Component* tempComponent) :Decorator(tempComponent) {}
	virtual void Operation() {
		Decorator::Operation();
		cout << "ConcreteDecoratorB" << endl;
	}
};

int main() {
	Component* component = new ConcreteComponent;
	component->Operation();

	Component* componentA = new ConcreteDecoratorA(component);
	componentA->Operation();

	Component* componentB = new ConcreteDecoratorB(component);
	componentB->Operation();

	return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hank_W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值