装饰器模式通过组合方式在不修改原始类的情况下动态扩展对象功能,C++中利用继承与指针成员实现Component、ConcreteComponent、Decorator和ConcreteDecorator角色,示例中PlainText作为基础文本,BoldText与ItalicText依次装饰,最终输出嵌套HTML标签的“Hello World”,体现了运行时灵活叠加行为的优势,符合开闭原则,但需注意装饰链长度、内存管理及装饰顺序对结果的影响。

装饰器模式的核心是在不修改原始类的前提下,动态地给对象添加新功能。C++中可以通过继承和组合的方式实现这一设计模式,尤其适合需要在运行时灵活扩展功能的场景。
装饰器模式的基本结构
该模式包含以下几个关键角色:
- Component(组件接口):定义对象的公共接口,可以是抽象类或接口。
- ConcreteComponent(具体组件):实现基本功能的对象。
- Decorator(装饰器基类):持有 Component 指针,并实现相同的接口。
- ConcreteDecorator(具体装饰器):在原有功能基础上添加新行为。
代码实现示例
下面是一个简单的文本显示功能的装饰器实现:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
<p>// 组件接口
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string getContent() const = 0;
};</p><p>// 具体组件:基础文本
class PlainText : public TextComponent {
std::string text;
public:
explicit PlainText(const std::string& t) : text(t) {}
std::string getContent() const override {
return text;
}
};</p><p>// 装饰器基类
class TextDecorator : public TextComponent {
protected:
TextComponent<em> component;
public:
explicit TextDecorator(TextComponent</em> c) : component(c) {}
virtual ~TextDecorator() { delete component; }
std::string getContent() const override {
return component->getContent();
}
};</p><p>// 具体装饰器:加粗
class BoldText : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string getContent() const override {
return "<b>" + component->getContent() + "</b>";
}
};</p><p>// 具体装饰器:斜体
class ItalicText : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string getContent() const override {
return "<i>" + component->getContent() + "</i>";
}
};</p>使用方式如下:
int main() {
TextComponent* text = new PlainText("Hello World");
text = new BoldText(text);
text = new ItalicText(text);
<pre class='brush:php;toolbar:false;'>std::cout << text->getContent() << std::endl;
// 输出: <b><i>Hello World</i></b>
delete text; // 自动释放内部对象
return 0;}
优势与注意事项
这种实现方式的优点在于:
- 可以在运行时动态组合功能,而不是编译时固定行为。
- 避免了通过继承产生大量子类的问题。
- 符合开闭原则:对扩展开放,对修改关闭。
需要注意的地方:
- 装饰器链过长可能影响性能。
- 内存管理要小心,建议使用智能指针替代裸指针。
- 多个装饰器之间的顺序可能影响最终结果。
基本上就这些。装饰器模式在需要逐步增强对象能力时非常实用,比如日志、权限校验、缓存等功能的叠加。关键是保持接口一致,让客户端无感知地使用被装饰后的对象。










