装饰器模式通过组合方式动态扩展对象功能,示例中Widget接口的TextField被BorderDecorator和ScrollDecorator逐层包装,调用draw时形成“添加滚动条→绘制文本→添加边框”的行为链,体现了运行时灵活增强特性。

装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许动态地为对象添加功能,而无需修改其原有代码。在 C++ 中,通过继承与组合的方式可以很好地实现这一模式。相比继承,装饰器更灵活,可以在运行时动态扩展对象行为。
装饰器模式的核心是:
下面是一个简单的示例:为文本显示功能添加边框、滚动条等装饰效果。
#include <iostream>
#include <string>
// 组件基类
class Widget {
public:
virtual ~Widget() = default;
virtual void draw() const = 0;
};
// 具体组件:基础文本框
class TextField : public Widget {
std::string text;
public:
explicit TextField(const std::string& t) : text(t) {}
void draw() const override {
std::cout << "Drawing text field with: '" << text << "'\n";
}
};装饰器也继承自 Widget,并持有一个 Widget 指针,在其基础上添加功能。
立即学习“C++免费学习笔记(深入)”;
// 装饰器基类
class WidgetDecorator : public Widget {
protected:
Widget* widget;
public:
explicit WidgetDecorator(Widget* w) : widget(w) {}
void draw() const override {
widget->draw(); // 默认转发调用
}
};
// 添加边框的装饰器
class BorderDecorator : public WidgetDecorator {
public:
explicit BorderDecorator(Widget* w) : WidgetDecorator(w) {}
void draw() const override {
WidgetDecorator::draw();
std::cout << " + Adding border\n";
}
};
// 添加滚动条的装饰器
class ScrollDecorator : public WidgetDecorator {
public:
explicit ScrollDecorator(Widget* w) : WidgetDecorator(w) {}
void draw() const override {
std::cout << " + Adding scrollbars\n";
WidgetDecorator::draw();
}
};你可以像搭积木一样组合多个装饰器。
int main() {
// 创建原始组件
Widget* input = new TextField("Hello");
// 动态添加功能
Widget* withBorder = new BorderDecorator(input);
Widget* withScroll = new ScrollDecorator(withBorder);
// 执行绘制
withScroll->draw();
// 注意:实际中应使用智能指针管理内存
delete withScroll; // 会递归释放所有包装层
return 0;
}输出结果:
+ Adding scrollbars Drawing text field with: 'Hello' + Adding border
std::unique_ptr 或 std::shared_ptr 管理所有权。若想支持自动内存管理,可将构造参数改为智能指针,或让装饰器接管所包装对象的生命周期。
基本上就这些。装饰器模式在 GUI 组件、流处理、日志系统中非常实用。
以上就是c++++怎么实现一个装饰器(Decorator)设计模式_c++装饰器模式实现与应用的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号