装饰器模式通过组合动态扩展对象功能,核心角色包括Component、ConcreteComponent、Decorator和ConcreteDecorator,以统一接口为基础,在不修改原类的前提下叠加行为,适用于文本样式、日志系统、数据流处理等场景,结合智能指针可提升内存安全性。

在C++中实现装饰器设计模式,核心是通过组合而非继承来动态扩展对象功能。它允许在运行时为某个对象添加新行为,同时不影响同类其他对象。这种模式特别适合需要灵活叠加功能的场景,比如图形界面控件、输入输出流处理等。
装饰器模式包含以下几个角色:
下面是一个简单示例,展示如何为一个文本显示功能逐步添加加粗、斜体等样式:
#include <iostream>
#include <string>
// 组件接口
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:
explicit BoldText(TextComponent* c) : TextDecorator(c) {}
std::string display() const override {
return "<b>" + TextDecorator::display() + "</b>";
}
};
// 具体装饰器:斜体
class ItalicText : public TextDecorator {
public:
explicit ItalicText(TextComponent* c) : TextDecorator(c) {}
std::string display() const override {
return "<i>" + TextDecorator::display() + "</i>";
}
};使用方式如下:
立即学习“C++免费学习笔记(深入)”;
int main() {
TextComponent* text = new PlainText("Hello World");
text = new BoldText(text); // 加粗
text = new ItalicText(text); // 再斜体
std::cout << text->display() << std::endl;
// 输出: <i><b>Hello World</b></i>
delete text; // 自动释放链式资源
return 0;
}装饰器的优势在于可层层包装,每个装饰器只关注自己的职责。你可以根据条件决定是否应用某种装饰,比如只对特定用户加特效:
TextComponent* createStyledText(const std::string& content, bool bold, bool italic) {
TextComponent* result = new PlainText(content);
if (bold) result = new BoldText(result);
if (italic) result = new ItalicText(result);
return result;
}原始实现中手动管理内存容易出错。更现代的写法应使用std::unique_ptr避免泄漏:
#include <memory>
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string display() const = 0;
};
using TextPtr = std::unique_ptr<TextComponent>;
class TextDecorator : public TextComponent {
protected:
TextPtr component;
public:
explicit TextDecorator(TextPtr c) : component(std::move(c)) {}
// display() 同上,调用 component->display()
};这样外部无需手动 delete,RAII机制自动回收资源。
基本上就这些。只要把握“接口一致、内部持有、增强行为”的原则,就能灵活实现功能扩展而不污染原有类。
以上就是c++++如何实现一个装饰器设计模式_c++动态扩展对象功能的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号