装饰器模式在c++++中通过继承和组合实现,核心在于不修改现有类代码的前提下动态扩展对象功能。1. 定义抽象组件(component)提供统一接口;2. 创建具体组件(concretecomponent)作为基础对象;3. 抽象装饰器(decorator)实现相同接口并持有组件引用;4. 具体装饰器(concretedecorator)扩展功能;5. 使用智能指针管理装饰链,避免内存泄漏;6. 通过层层包装组合功能,避免类爆炸问题,符合开闭原则。

用C++实现装饰器模式,核心在于利用继承和组合的强大力量,在不触碰现有类代码的前提下,动态地为对象附加新的行为。这就像给一个普通物品不断地套上各种“皮肤”或“配件”,每套一个,它就多一个功能,而物品本身还是那个物品。

要实现装饰器模式,我们通常需要定义一个抽象组件(Component),它定义了被装饰对象和装饰器共同的接口。接着是具体的组件(ConcreteComponent),也就是我们想要增强的原始对象。然后是抽象装饰器(Decorator),它也实现组件接口,并包含一个指向组件对象的引用。最后是具体的装饰器(ConcreteDecorator),它们继承抽象装饰器,并实现或增强其行为。
下面是一个简单的C++例子,以一个“文本输出”功能为例:
立即学习“C++免费学习笔记(深入)”;

#include <iostream>
#include <string>
#include <memory> // for std::unique_ptr
// 1. 抽象组件 (Component)
// 定义了被装饰对象和装饰器都必须实现的接口
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string getContent() const = 0;
};
// 2. 具体组件 (ConcreteComponent)
// 原始的、未被装饰的类
class SimpleText : public TextComponent {
private:
std::string text_;
public:
SimpleText(const std::string& text) : text_(text) {}
std::string getContent() const override {
return text_;
}
};
// 3. 抽象装饰器 (Decorator)
// 实现了Component接口,并持有一个Component对象的引用
class TextDecorator : public TextComponent {
protected:
std::unique_ptr<TextComponent> wrappedComponent_; // 使用智能指针管理生命周期
public:
TextDecorator(std::unique_ptr<TextComponent> component)
: wrappedComponent_(std::move(component)) {}
// 装饰器也必须实现getContent,通常会调用被包装组件的getContent
std::string getContent() const override {
return wrappedComponent_->getContent();
}
};
// 4. 具体装饰器 (ConcreteDecorator) - 添加功能A
class BoldTextDecorator : public TextDecorator {
public:
BoldTextDecorator(std::unique_ptr<TextComponent> component)
: TextDecorator(std::move(component)) {}
std::string getContent() const override {
// 在原有内容基础上添加粗体标记
return "<b>" + wrappedComponent_->getContent() + "</b>";
}
};
// 5. 具体装饰器 (ConcreteDecorator) - 添加功能B
class ItalicTextDecorator : public TextDecorator {
public:
ItalicTextDecorator(std::unique_ptr<TextComponent> component)
: TextDecorator(std::move(component)) {}
std::string getContent() const override {
// 在原有内容基础上添加斜体标记
return "<i>" + wrappedComponent_->getContent() + "</i>";
}
};
// 6. 具体装饰器 (ConcreteDecorator) - 添加功能C
class UnderlineTextDecorator : public TextDecorator {
public:
UnderlineTextDecorator(std::unique_ptr<TextComponent> component)
: TextDecorator(std::move(component)) {}
std::string getContent() const override {
// 在原有内容基础上添加下划线标记
return "<u>" + wrappedComponent_->getContent() + "</u>";
}
};
// 客户端代码
int main() {
// 创建一个简单的文本
std::unique_ptr<TextComponent> myText = std::make_unique<SimpleText>("Hello, Decorator!");
std::cout << "Original text: " << myText->getContent() << std::endl;
// 装饰它:粗体
myText = std::make_unique<BoldTextDecorator>(std::move(myText));
std::cout << "Bold text: " << myText->getContent() << std::endl;
// 继续装饰:斜体 (在粗体的基础上)
myText = std::make_unique<ItalicTextDecorator>(std::move(myText));
std::cout << "Italic & Bold text: " << myText->getContent() << std::endl;
// 继续装饰:下划线 (在斜体和粗体的基础上)
myText = std::make_unique<UnderlineTextDecorator>(std::move(myText));
std::cout << "Underline, Italic & Bold text: " << myText->getContent() << std::endl;
// 也可以直接创建一个多重装饰的文本
std::unique_ptr<TextComponent> complexText =
std::make_unique<UnderlineTextDecorator>(
std::make_unique<BoldTextDecorator>(
std::make_unique<SimpleText>("Another example!")
)
);
std::cout << "Complex decorated text: " << complexText->getContent() << std::endl;
return 0;
}这段代码展示了如何通过层层包装,动态地为
SimpleText
SimpleText
说实话,初学者看到装饰器模式,可能第一反应是:“这不就是多重继承或者子类化可以解决的吗?”比如,如果我想一个
Window
ScrollableWindow
BorderedWindow
ScrollableBorderedWindow

但问题来了。设想一下,如果你的功能越来越多,比如还有阴影、标题栏、最小化按钮等等,这些功能可以任意组合。如果用继承,你很快就会陷入一个“类爆炸”的泥潭。你可能需要
ScrollableBorderedShadowedWindow
ScrollableTitledWindow
装饰器模式恰好解决了这个问题。它允许你将功能的添加从类的定义中剥离出来,转而通过对象组合的方式在运行时动态地添加。你只需要为每个独立的功能创建一个装饰器,然后像搭积木一样,把它们“套”在你的基础对象上。这符合“开闭原则”:对扩展开放,对修改关闭。你不需要修改
SimpleText
尽管装饰器模式非常优雅,但在实际应用中,它并非没有自己的小脾气。
首先,复杂性增加。当你有一堆装饰器层层嵌套时,代码的调用链会变得比较深。调试时,你可能需要一层层地“钻”进去,才能明白数据到底是怎么流转的。这不像直接调用一个方法那么直观。特别是如果每个装饰器都有自己的状态或复杂的逻辑,那就更需要小心了。
再来,对象的身份问题。当一个对象被装饰后,它就不再是原始的那个
ConcreteComponent
Component
dynamic_cast
Decorator
SimpleText
还有就是C++特有的内存管理。在我的示例中,我用了
std::unique_ptr
Component
delete
std::shared_ptr
最后,装饰器顺序的影响。在某些情况下,你应用装饰器的顺序可能会影响最终的行为。比如,你先加密再压缩,和先压缩再加密,结果可能完全不同。这要求你在设计和使用装饰器时,要清晰地理解每个装饰器的作用以及它们之间的依赖关系。这不是模式本身的缺点,而是使用它时需要多一份思考。
装饰器模式在实际项目中非常常见,它不只是一个独立的模式,很多时候它会悄悄地与其它设计模式协同工作,发挥更大的威力。
一个很典型的例子是它和工厂模式的结合。想象一下,你的系统需要根据用户的配置或者运行时的一些条件,动态地构建一个具有特定功能的文本处理管道。你可能不会直接在客户端代码里
new BoldTextDecorator(new ItalicTextDecorator(...))
另一个有趣的组合是与组合模式(Composite Pattern)。这俩兄弟有时候看起来有点像,因为它们都涉及递归结构和通过共同接口处理对象。组合模式关注的是“部分-整体”的层级结构,而装饰器模式则是在不改变对象接口的前提下,动态地为对象添加新职责。在某些复杂场景下,你可能会发现一个组合对象本身又被装饰器所装饰,或者装饰器内部又包含了一个组合对象。这有点像一个俄罗斯套娃,套娃里面又套着另一个套娃,只不过每个套娃都可能增加一些新的“玩法”。
在实际的软件库中,装饰器模式的身影无处不在。比如,Java的I/O流就是装饰器模式的经典应用。你可以把一个
FileInputStream
BufferedInputStream
DataInputStream
以上就是如何用C++实现装饰器模式 动态添加功能不修改原有类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号