
装饰器模式(Decorator Pattern)在C++中是一种结构型设计模式,它允许动态地为对象添加新功能,而无需修改原有类的代码。与继承不同,装饰器通过组合的方式在运行时扩展对象行为,更加灵活。
装饰器模式的关键在于:
这种结构让你可以像“套娃”一样层层包装对象,每层增加一个功能。
以下是一个简单的例子,展示如何用装饰器模式给文本显示功能添加格式化效果:
立即学习“C++免费学习笔记(深入)”;
// 共同接口 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: explicit BoldText(TextComponent* c) : TextDecorator(c) {} std::string getContent() const override { return "" + TextDecorator::getContent() + ""; } };
// 具体装饰器:斜体 class ItalicText : public TextDecorator { public: explicit ItalicText(TextComponent* c) : TextDecorator(c) {} std::string getContent() const override { return "" + TextDecorator::getContent() + ""; } };
使用方式:
int main() { TextComponent* text = new PlainText("Hello World"); text = new BoldText(text); text = new ItalicText(text);std::cout << text->getContent() << std::endl; // 输出: <i><b>Hello World</b></i> delete text; // 自动释放内部对象 return 0;
}
在真实项目中,可以这样改进装饰器模式的使用:
例如改用智能指针后,TextDecorator可改为:
class TextDecorator : public TextComponent { protected: std::unique_ptr基本上就这些。装饰器模式适合需要灵活扩展功能的场景,比如GUI组件、输入输出流处理、日志系统等。关键是设计好基础接口,然后通过组合不断叠加能力,而不是靠继承爆炸式增长子类。
以上就是C++如何使用装饰器模式扩展功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号