装饰器模式通过包装对象动态扩展功能,C++中结合继承、组合与智能指针可实现安全灵活的装饰结构,适用于GUI样式、日志等需动态添加行为的场景。
装饰器模式是一种结构型设计模式,它允许在不修改对象本身的前提下动态地为对象添加新功能。在C++中,通过继承和组合的方式可以很好地实现这一模式,尤其适用于需要灵活扩展功能的场景。
装饰器模式通过“包装”原始对象来增强其行为。被装饰的对象与装饰器实现相同的接口,客户端无需关心具体是原始对象还是被装饰过的对象。
关键点包括:
以下是一个简单的文本显示功能的装饰示例:
#include#include // 组件接口 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: using TextDecorator::TextDecorator; std::string display() const override { return "" + TextDecorator::display() + ""; } };
// 具体装饰器:斜体 class ItalicText : public TextDecorator { public: using TextDecorator::TextDecorator; std::string display() const override { return "" + TextDecorator::display() + ""; } };
使用方式如下:
int main() {
TextComponent* text = new PlainText("Hello World");
text = new BoldText(text);
text = new ItalicText(text);
std::cout zuojiankuohaophpcnzuojiankuohaophpcn text-youjiankuohaophpcndisplay() zuojiankuohaophpcnzuojiankuohaophpcn std::endl;
// 输出: zuojiankuohaophpcnbyoujiankuohaophpcnzuojiankuohaophpcniyoujiankuohaophpcnHello Worldzuojiankuohaophpcn/iyoujiankuohaophpcnzuojiankuohaophpcn/byoujiankuohaophpcn
delete text;
return 0;
}
上述实现存在裸指针管理的问题。可以借助智能指针提升安全性:
例如,将TextDecorator改为:
class TextDecorator : public TextComponent {
protected:
std::unique_ptr component;
public:
explicit TextDecorator(std::unique_ptr c)
: component(std::move(c)) {}
// display() 同样转发调用
};
装饰器适合用于:

注意点:
基本上就这些。C++中实现装饰器模式的关键在于清晰的接口划分和资源管理。结合现代C++特性能让代码更安全、更易维护。