装饰器模式通过组合动态扩展对象功能,核心角色包括Component、ConcreteComponent、Decorator和ConcreteDecorator,以统一接口为基础,在不修改原类的前提下叠加行为,适用于文本样式、日志系统、数据流处理等场景,结合智能指针可提升内存安全性。

在c++中实现装饰器设计模式,核心是通过组合而非继承来动态扩展对象功能。它允许在运行时为某个对象添加新行为,同时不影响同类其他对象。这种模式特别适合需要灵活叠加功能的场景,比如图形界面控件、输入输出流处理等。
装饰器模式的基本结构
装饰器模式包含以下几个角色:
- Component(组件接口):定义对象的统一接口,可以是抽象类或纯虚类。
- ConcreteComponent(具体组件):实现基本功能的对象。
- Decorator(装饰器基类):持有Component指针,并实现相同接口,通常也继承自Component。
- ConcreteDecorator(具体装饰器):在调用原对象方法前后添加额外逻辑。
下面是一个简单示例,展示如何为一个文本显示功能逐步添加加粗、斜体等样式:
#include <iostream> #include <string> // 组件接口 class TextComponent { public: virtual ~TextComponent() = default; virtual std::string display() const = 0; }; // 具体组件:基础文本 class PlainText : public TextComponent { std::string text; public: explicit PlainText(const std::string& t) : text(t) {} std::string display() const override { return text; } }; // 装饰器基类 class TextDecorator : public TextComponent { protected: TextComponent* component; public: explicit TextDecorator(TextComponent* c) : component(c) {} virtual ~TextDecorator() { delete component; } std::string display() const override { return component->display(); } }; // 具体装饰器:加粗 class BoldText : public TextDecorator { public: explicit BoldText(TextComponent* c) : TextDecorator(c) {} std::string display() const override { return "<b>" + TextDecorator::display() + "</b>"; } }; // 具体装饰器:斜体 class ItalicText : public TextDecorator { public: explicit ItalicText(TextComponent* c) : TextDecorator(c) {} std::string display() const override { return "<i>" + TextDecorator::display() + "</i>"; } };
使用方式如下:
立即学习“C++免费学习笔记(深入)”;
int main() { TextComponent* text = new PlainText("Hello World"); text = new BoldText(text); // 加粗 text = new ItalicText(text); // 再斜体 std::cout << text->display() << std::endl; // 输出: <i><b>Hello World</b></i> delete text; // 自动释放链式资源 return 0; }
支持多层嵌套与独立控制
装饰器的优势在于可层层包装,每个装饰器只关注自己的职责。你可以根据条件决定是否应用某种装饰,比如只对特定用户加特效:
TextComponent* createStyledText(const std::string& content, bool bold, bool italic) { TextComponent* result = new PlainText(content); if (bold) result = new BoldText(result); if (italic) result = new ItalicText(result); return result; }
改进内存管理(推荐使用智能指针)
原始实现中手动管理内存容易出错。更现代的写法应使用std::unique_ptr避免泄漏:
#include <memory> class TextComponent { public: virtual ~TextComponent() = default; virtual std::string display() const = 0; }; using TextPtr = std::unique_ptr<TextComponent>; class TextDecorator : public TextComponent { protected: TextPtr component; public: explicit TextDecorator(TextPtr c) : component(std::move(c)) {} // display() 同上,调用 component->display() };
这样外部无需手动 delete,RAII机制自动回收资源。
实际应用场景建议
基本上就这些。只要把握“接口一致、内部持有、增强行为”的原则,就能灵活实现功能扩展而不污染原有类。