Update 设计模式 - 桥接.md

补充类图说明与双维度扩展对比,补充示例运行输出,更新 JDK 中 AWT 与 JDBC 的应用说明并进行文字校对。
This commit is contained in:
CyC2018
2026-10-30 20:19:44 +08:00
parent a669d4ad1e
commit fc04b93602
+24 -11
View File
@@ -1,13 +1,11 @@
## 桥接(Bridge)
### 意图
将抽象与实现分离开来,使它们可以独立变化。
### 类图
- Abstraction:定义抽象类的接口
- Implementor:定义实现类接口
- Abstraction:定义抽象类的接口,并持有一个 Implementor 的引用;
- Implementor:定义实现类接口。
<div align="center"> <img src="pics/dp-bridge.png" width="760px"/> </div><br>
@@ -16,7 +14,7 @@ RemoteControl 表示遥控器,指代 Abstraction。
TV 表示电视,指代 Implementor。
桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。
桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。如果用继承同时表达这两个维度,2 种遥控器 × 2 种电视需要 4 个子类,再加一种电视又要加 2 个;让遥控器持有一个 TV 引用以后,两个维度各自扩展,类的数量从相乘变为相加。
```java
public abstract class TV {
@@ -142,18 +140,33 @@ public class Client {
remoteControl1.off();
remoteControl1.tuneChannel();
RemoteControl remoteControl2 = new ConcreteRemoteControl2(new Sony());
remoteControl2.on();
remoteControl2.off();
remoteControl2.tuneChannel();
remoteControl2.on();
remoteControl2.off();
remoteControl2.tuneChannel();
}
}
```
```text
ConcreteRemoteControl1.on()
RCA.on()
ConcreteRemoteControl1.off()
RCA.off()
ConcreteRemoteControl1.tuneChannel()
RCA.tuneChannel()
ConcreteRemoteControl2.on()
Sony.on()
ConcreteRemoteControl2.off()
Sony.off()
ConcreteRemoteControl2.tuneChannel()
Sony.tuneChannel()
```
### JDK 中的应用
- AWT (It provides an abstraction layer which maps onto the native OS the windowing support.)
- JDBC
- AWT:组件类是抽象,java.awt.peer 中与平台相关的 peer 是实现,把窗口功能映射到不同的操作系统;
- JDBC:应用面向 JDBC 接口编程,各数据库厂商的驱动是实现。
## 参考资料
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
- Gamma E. 设计模式:可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.