装饰器模式通过组合方式在不修改原始类的情况下动态扩展对象功能,C++中利用继承与指针成员实现Component、ConcreteComponent、Decorator和ConcreteDecorator角色,示例中PlainText作为基础文本,BoldText与ItalicText依次装饰,最终输出嵌套HTML标签的“Hello World”,体现了运行时灵活叠加行为的优势,符合开闭原则,但需注意装饰链长度、内存管理及装饰顺序对结果的影响。
装饰器模式的核心是在不修改原始类的前提下,动态地给对象添加新功能。C++中可以通过继承和组合的方式实现这一设计模式,尤其适合需要在运行时灵活扩展功能的场景。
该模式包含以下几个关键角色:
下面是一个简单的文本显示功能的装饰器实现:
#include#include // 组件接口 class TextComponent { public: virtual ~TextComponent() = default; virtual std::string getContent() const = 0; };
// 具体组件:基础文本 class PlainText : public TextComponent { std::string text; public: explicit PlainText(const std::string& t) : text(t) {} std::string getContent() const override { return text; } };
// 装饰器基类 class TextDecorator : public TextComponent { protected: TextComponent component; public: explicit TextDecorator(TextComponent c) : component(c) {} virtual ~TextDecorator() { delete component; } std::string getContent() const override { return component->getContent(); } };
// 具体装饰器:加粗 class BoldText : public TextDecorator { public: using TextDecorator::TextDecorator; std::string getContent() const override { return "" + component->getContent() + "";
} };
// 具体装饰器:斜体 class ItalicText : public TextDecorator { public: using TextDecorator::TextDecorator; std::string getContent() const override { return "" + component->getContent() + ""; } };
使用方式如下:
int main() {
TextComponent* text = new PlainText("Hello World");
text = new BoldText(text);
text = new ItalicText(text);
std::cout zuojiankuohaophpcnzuojiankuohaophpcn text->getContent() zuojiankuohaophpcnzuojiankuohaophpcn std::endl;
// 输出: zuojiankuohaophpcnbyoujiankuohaophpcnzuojiankuohaophpcniyoujiankuohaophpcnHello Worldzuojiankuohaophpcn/iyoujiankuohaophpcnzuojiankuohaophpcn/byoujiankuohaophpcn
delete text; // 自动释放内部对象
return 0;
}
这种实现方式的优点在于:
需要注意的地方:
基本上就这些。装饰器模式在需要逐步增强对象能力时非常实用,比如日志、权限校验、缓存等功能的叠加。关键是保持接口一致,让客户端无感知地使用被装饰后的对象。