请用C++语言给出一个程序设计模式中的装饰模式
时间: 2024-05-15 18:16:01 浏览: 44
装饰模式是一种结构型设计模式,它允许在运行时通过添加新的行为或者修改现有行为来扩展对象的功能。
以下是一个使用装饰模式的示例程序:
```c
#include <stdio.h>
// 定义一个抽象组件
typedef struct {
void (*operation)(void);
} Component;
// 定义一个具体组件
typedef struct {
Component component;
} ConcreteComponent;
// 定义一个装饰器
typedef struct {
Component *component;
} Decorator;
// 定义一个具体装饰器A
typedef struct {
Decorator decorator;
} ConcreteDecoratorA;
// 定义一个具体装饰器B
typedef struct {
Decorator decorator;
} ConcreteDecoratorB;
// 实现抽象组件的操作
void operation(Component *component) {
printf("Operation of Component.\n");
}
// 实现具体组件的操作
void concrete_operation(ConcreteComponent *component) {
printf("Operation of Concrete Component.\n");
}
// 实现装饰器的操作
void decorator_operation(Decorator *decorator) {
printf("Decorator Operation.\n");
decorator->component->operation(decorator->component);
}
// 实现具体装饰器A的操作
void concrete_decorator_a_operation(ConcreteDecoratorA *decorator) {
printf("Concrete Decorator A Operation.\n");
decorator_operation((Decorator *)decorator);
}
// 实现具体装饰器B的操作
void concrete_decorator_b_operation(ConcreteDecoratorB *decorator) {
printf("Concrete Decorator B Operation.\n");
decorator_operation((Decorator *)decorator);
}
int main() {
ConcreteComponent component;
ConcreteDecoratorA decorator_a;
ConcreteDecoratorB decorator_b;
// 将具体组件包装成具体装饰器A并调用其操作
decorator_a.decorator.component = (Component *)&component;
concrete_decorator_a_operation(&decorator_a);
// 将具体装饰器A包装成具体装饰器B并调用其操作
decorator_b.decorator.component = (Component *)&decorator_a;
concrete_decorator_b_operation(&decorator_b);
return 0;
}
```
在上述示例程序中,我们定义了一个抽象组件 `Component` 和一个具体组件 `ConcreteComponent`,它们都有一个 `operation` 方法。我们还定义了一个装饰器 `Decorator` 和两个具体装饰器 `ConcreteDecoratorA` 和 `ConcreteDecoratorB`,它们也有一个 `operation` 方法,并且在执行时会调用包装的组件的 `operation` 方法。
在 `main` 函数中,我们首先将具体组件包装成具体装饰器A并调用其操作,然后将具体装饰器A包装成具体装饰器B并调用其操作。这样就实现了在运行时动态扩展对象的功能。