装饰器模式通过包装对象动态扩展功能,C++中结合继承、组合与智能指针可实现安全灵活的装饰结构,适用于GUI样式、日志等需动态添加行为的场景。

装饰器模式是一种结构型设计模式,它允许在不修改对象本身的前提下动态地为对象添加新功能。在C++中,通过继承和组合的方式可以很好地实现这一模式,尤其适用于需要灵活扩展功能的场景。
装饰器模式通过“包装”原始对象来增强其行为。被装饰的对象与装饰器实现相同的接口,客户端无需关心具体是原始对象还是被装饰过的对象。
关键点包括:
以下是一个简单的文本显示功能的装饰示例:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
<p>// 组件接口
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string display() const = 0;
};</p><p>// 具体组件
class PlainText : public TextComponent {
std::string text;
public:
explicit PlainText(const std::string& t) : text(t) {}
std::string display() 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 display() const override {
return component->display();
}
};</p><p>// 具体装饰器:加粗
class BoldText : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string display() const override {
return "<b>" + TextDecorator::display() + "</b>";
}
};</p><p>// 具体装饰器:斜体
class ItalicText : public TextDecorator {
public:
using TextDecorator::TextDecorator;
std::string display() const override {
return "<i>" + TextDecorator::display() + "</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->display() << std::endl;
// 输出: <b><i>Hello World</i></b>
delete text;
return 0;}
上述实现存在裸指针管理的问题。可以借助智能指针提升安全性:
例如,将TextDecorator改为:
class TextDecorator : public TextComponent {
protected:
std::unique_ptr<TextComponent> component;
public:
explicit TextDecorator(std::unique_ptr<TextComponent> c)
: component(std::move(c)) {}
// display() 同样转发调用
};
装饰器适合用于:
注意点:
基本上就这些。C++中实现装饰器模式的关键在于清晰的接口划分和资源管理。结合现代C++特性能让代码更安全、更易维护。
以上就是C++如何实现装饰器模式_C++设计模式与装饰器实现技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号