Cplusplus装饰器模式
时间: 2023-09-21 11:03:02 浏览: 52
装饰器模式是一种结构型设计模式,它允许在运行时动态地给一个对象添加新的行为,而不会影响其他对象。该模式通过将对象封装在一个装饰器类中,然后在运行时添加装饰器来实现。这种方法比继承更加灵活,因为它允许您在运行时选择要添加的装饰器,而不是在编译时决定。
在 C++ 中,装饰器模式可以通过以下步骤来实现:
1. 定义一个基类(或接口),表示要被装饰的组件。
2. 定义一个装饰器类,该类继承自基类,并包含一个指向基类对象的指针成员变量。
3. 在装饰器类中实现基类的接口,并在其中添加一些新的行为(例如,在执行基类方法之前或之后执行某些操作)。
4. 在客户端代码中创建一个基类对象,并将其作为参数传递给一个或多个装饰器对象。
下面是一个简单的示例代码,其中定义了一个基类 `Component` 和两个装饰器类 `DecoratorA` 和 `DecoratorB`:
```c++
#include <iostream>
class Component {
public:
virtual void operation() = 0;
};
class ConcreteComponent : public Component {
public:
void operation() override {
std::cout << "ConcreteComponent operation" << std::endl;
}
};
class DecoratorA : public Component {
public:
DecoratorA(Component* component) : component_(component) {}
void operation() override {
std::cout << "DecoratorA operation" << std::endl;
component_->operation();
}
private:
Component* component_;
};
class DecoratorB : public Component {
public:
DecoratorB(Component* component) : component_(component) {}
void operation() override {
std::cout << "DecoratorB operation" << std::endl;
component_->operation();
}
private:
Component* component_;
};
```
在上面的示例中,`ConcreteComponent` 是一个实现了 `Component` 接口的基础类。`DecoratorA` 和 `DecoratorB` 是两个装饰器类,它们继承自 `Component` 接口,并包含一个指向 `Component` 对象的指针成员变量。在 `DecoratorA` 和 `DecoratorB` 类中,它们实现了 `Component` 接口,并在其中添加了新的行为。
在客户端代码中,我们可以创建一个 `ConcreteComponent` 对象,并将其作为参数传递给一个或多个装饰器对象:
```c++
int main() {
Component* component = new ConcreteComponent();
component = new DecoratorA(component);
component = new DecoratorB(component);
component->operation();
return 0;
}
```
在上面的示例中,我们创建了一个 `ConcreteComponent` 对象,并将其传递给 `DecoratorA` 和 `DecoratorB` 对象。最后,我们调用 `component->operation()` 方法,它会依次调用 `DecoratorB::operation()`、`DecoratorA::operation()` 和 `ConcreteComponent::operation()` 方法,并输出以下结果:
```
DecoratorB operation
DecoratorA operation
ConcreteComponent operation
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)