1. 装饰器模式:给C++对象动态"穿衣服"
第一次听说装饰器模式时,我正被一个需求折磨得焦头烂额:需要为图形界面组件动态添加边框、阴影、滚动条等功能,但又不想通过继承创建无数子类。直到在《设计模式》中看到装饰器(Decorator)这个精妙的解决方案——它就像给对象穿衣服一样,可以层层叠加新功能而不改变原有结构。
装饰器模式的核心在于"动态扩展"。想象你有一个核心的TextView对象,通过装饰器可以依次给它"穿上"BorderDecorator、ScrollDecorator、ShadowDecorator这些"外衣",每件"衣服"都赋予对象新的特性。这种设计完美遵循了开放-封闭原则:对扩展开放,对修改关闭。
在C++中实现装饰器模式有几个关键优势:
- 避免继承导致的类爆炸(比如TextViewWithBorderAndScrollAndShadow...)
- 运行时动态添加/移除功能(静态继承无法做到)
- 保持接口一致性(装饰器和原组件实现相同接口)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 装饰器模式的UML结构与C++实现
2.1 经典UML结构解析
先看装饰器模式的标准化结构(以图形组件为例):
code复制 _________________________
| Component |
|-------------------------|
| + operation(): void |
|_________↑_______________|
|
______________|_________________
| |
_________|_________ ___________|___________
| ConcreteComponent | | Decorator |
|---------------------| |-----------------------|
| + operation(): void | | - component: Component|
|_____________________| | + operation(): void |
|_______________________|
↑
_______________|_______________
| |
_____________|_________ _________|___________
| ConcreteDecoratorA | | ConcreteDecoratorB |
|-----------------------| |-----------------------|
| + operation(): void | | + operation(): void |
| + addedBehavior(): void| | + addedBehavior(): void|
|_______________________| |_______________________|
2.2 C++实现示例
下面是一个完整的C++实现(以文本处理为例):
cpp复制#include <iostream>
#include <string>
// 抽象组件接口
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string getText() const = 0;
};
// 具体组件
class PlainText : public TextComponent {
std::string text;
public:
explicit PlainText(const std::string& t) : text(t) {}
std::string getText() const override { return text; }
};
// 抽象装饰器
class TextDecorator : public TextComponent {
protected:
TextComponent* component;
public:
explicit TextDecorator(TextComponent* c) : component(c) {}
std::string getText() const override { return component->getText(); }
};
// 具体装饰器:添加HTML标签
class HtmlDecorator : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string getText() const override {
return "<html>" + component->getText() + "</html>";
}
};
// 具体装饰器:添加Markdown强调
class MarkdownDecorator : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string getText() const override {
return "**" + component->getText() + "**";
}
};
// 使用示例
int main() {
TextComponent* text = new PlainText("Hello, Design Patterns!");
// 动态添加装饰
text = new HtmlDecorator(text);
text = new MarkdownDecorator(text);
