C++ 装饰器模式

装饰器模式用于解决C++中因功能扩展导致的子类膨胀问题,提供了一种更灵活的替代继承的方式。通过组合而非继承,装饰器模式允许动态地给对象添加新的职责,简化了类的扩展和维护。

装饰器模式

  1. 装饰器模式主要解决的是直接继承下因功能的不断横向扩展导致子类膨胀的问题,用装饰器模式后就会比直接继承显得更加灵活同时这样也就不再需要考虑子类的维护。
  2. 为了实现动态的给对象添加职能,即从外部给对象添加相关职能.
  3. 为了解决新加类职责,继承实现的弊端. 而是通过组合来实现.
    在这里插入图片描述
    抽象构件角色(Component)——定义抽象接口
    具体构件角色(ConcreteComponent)——实现抽象接口,可以是一组
    装饰角色(Decorator)——定义抽象类并继承接口中的方法,保证一致性
    具体装饰角色(ConcreteDecorator)——扩展装饰具体的实现逻辑
class Component
{
   
   
public:
	virtual 
装饰器模式是一种结构性设计模式,它允许你动态地向对象添加行为。在该模式中,你可以使用一系列包装器来包装具有相同接口的对象,以便它们可以相互替换。下面是一个简单的 C++ 装饰器模式实现示例: ```c++ #include <iostream> #include <memory> using namespace std; // 抽象组件 class Component { public: virtual void operation() = 0; }; // 具体组件 class ConcreteComponent : public Component { public: void operation() override { cout << "ConcreteComponent" << endl; } }; // 抽象装饰器 class Decorator : public Component { private: unique_ptr<Component> component; public: Decorator(unique_ptr<Component> component) : component(move(component)) {} void operation() override { component->operation(); } }; // 具体装饰器 class ConcreteDecoratorA : public Decorator { public: ConcreteDecoratorA(unique_ptr<Component> component) : Decorator(move(component)) {} void operation() override { Decorator::operation(); cout << "ConcreteDecoratorA" << endl; } }; class ConcreteDecoratorB : public Decorator { public: ConcreteDecoratorB(unique_ptr<Component> component) : Decorator(move(component)) {} void operation() override { Decorator::operation(); cout << "ConcreteDecoratorB" << endl; } }; int main() { unique_ptr<Component> component = make_unique<ConcreteComponent>(); unique_ptr<Component> decoratorA = make_unique<ConcreteDecoratorA>(move(component)); unique_ptr<Component> decoratorB = make_unique<ConcreteDecoratorB>(move(decoratorA)); decoratorB->operation(); return 0; } ``` 在上面的示例中,我们定义了一个抽象组件 `Component`,一个具体组件 `ConcreteComponent`,一个抽象装饰器 `Decorator`,以及两个具体装饰器 `ConcreteDecoratorA` 和 `ConcreteDecoratorB`。 在 `Decorator` 中,我们使用了一个指向 `Component` 的指针来持有一个组件对象,并实现了 `Component` 接口。在 `ConcreteDecoratorA` 和 `ConcreteDecoratorB` 中,我们通过调用 `Decorator` 的 `operation()` 方法来执行基础操作,并添加自己的操作。 在 `main()` 函数中,我们首先创建了一个具体组件 `ConcreteComponent` 对象,然后使用 `ConcreteDecoratorA` 和 `ConcreteDecoratorB` 装饰它。最后,我们调用 `decoratorB` 的 `operation()` 方法来执行所有操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

比滕

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

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

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

打赏作者

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

抵扣说明:

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

余额充值