C语言实现结构型模式:适配器、桥接、装饰器、组合
导读:结构型设计模式关注如何组合类与对象形成更大结构。本文介绍适配器、桥接、装饰器、组合四种模式,全部代码可直接编译运行,适合想提升C语言工程能力的开发者。
一、原理简析
结构型模式的核心思想是组合优于继承。通过对象组合,可以更灵活地构建复杂系统,同时避免继承带来的类爆炸问题。
四种模式对比:
| 模式 | 核心作用 | 解决问题 |
|---|---|---|
| 适配器 | 接口转换 | 让不兼容的接口合作 |
| 桥接 | 分离抽象与实现 | 多维度独立变化 |
| 装饰器 | 动态添加功能 | 功能叠加更灵活 |
| 组合 | 树形结构 | 部分-整体层次 |
二、实操步骤
2.1 适配器模式:接口转换
#include <stdio.h>
void Old220VPower(void) {
printf("旧设备:220V 供电\n");
}
typedef struct TargetPower {
void (*Supply)(void);
} TargetPower;
void AdapterSupply(void) {
printf("适配器:电压转换中...\n");
Old220VPower();
}
int main(void) {
TargetPower t = {AdapterSupply};
t.Supply();
return 0;
}
2.2 桥接模式:分离抽象与实现
#include <stdio.h>
typedef struct Color {
void (*ShowColor)(void);
} Color;
void RedColor(void) { printf("红色\n"); }
void BlueColor(void) { printf("蓝色\n"); }
typedef struct Shape {
Color *color;
void (*Draw)(struct Shape*);
} Shape;
void DrawShape(Shape* s) {
printf("绘制图形,颜色:");
s->color->ShowColor();
}
2.3 装饰器模式:动态添加功能
#include <stdio.h>
typedef struct Coffee {
int (*Cost)(void);
void (*Info)(void);
} Coffee;
int SimpleCost(void) { return 10; }
void SimpleInfo(void){ printf("基础咖啡 "); }
int MilkCost(void) { return 15; }
void MilkInfo(void) { printf("加牛奶 "); }
int main(void) {
Coffee base = {SimpleCost, SimpleInfo};
Coffee milk = {MilkCost, MilkInfo};
base.Info();
printf("价格:%d元\n", base.Cost());
milk.Info();
printf("价格:%d元\n", milk.Cost());
return 0;
}
2.4 组合模式:树形结构
#include <stdio.h>
#include <string.h>
typedef struct Component {
char name[20];
void (*Show)(int depth);
} Component;
void LeafShow(Component* leaf, int d) {
for(int i=0; i<d; i++) printf(" ");
printf("- %s(叶子)\n", leaf->name);
}
void CompositeShow(Component* self, int d, Component** children, int count) {
for(int i=0; i<d; i++) printf(" ");
printf("+ %s(容器)\n", self->name);
for(int i=0; i<count; i++) {
children[i]->Show(children[i], d+1);
}
}
三、对比表格
|
适配器模式 接口转换 | 包装旧接口 | 让不兼容合作 |
| ↓ |
|
桥接模式 分离抽象与实现 | 双维度组合 | 独立变化 |
| ↓ |
|
装饰器模式 动态添加 | 功能叠加 | 比继承更灵活 |
| ↓ |
|
组合模式 树形结构 | 递归包含 | 部分-整体层次 |
四、核心流程图
flowchart TB
subgraph 结构型模式["结构型模式"]
A["适配器<br/>接口转换"]
B["桥接模式<br/>分离抽象与实现"]
C["装饰器<br/>动态添加功能"]
D["组合模式<br/>树形结构"]
end
A --> B
B --> C
C --> D
五、常见问题解决
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 装饰器vs继承 | 继承类爆炸 | 使用装饰器组合功能 |
| 桥接模式复杂度高 | 过度设计 | 仅在多维度变化时使用 |
| 组合模式遍历 | 递归开销 | 考虑迭代替代递归 |
六、总结
本文介绍了4种结构型设计模式。核心思想是组合优于继承,通过对象组合灵活构建复杂系统。
来自 linuxros.cn · linuxROS
核心要点:
- 适配器:让不兼容的接口合作
- 桥接:抽象与实现分离独立变化
- 装饰器:动态添加功能比继承更灵活
- 组合:树形结构表示部分-整体层次
下期预告:《C语言实现结构型模式:外观、享元、代理》—— 剩余3种结构型模式详解。
关注公众号:linuxros
回复「设计模式」,获取完整23种设计模式C语言实现源码