设计模式-桥街模式

发布于 — 2019 年 10 月 14 日
#design

抽离一套接口, 下面可以有多种实现.

原理解析

桥接模式, 也叫做桥梁模式(Bridge Design Pattern), 将抽象和实现解耦, 让他们可以独立变化.

这里的抽象, 并非指的是"抽象类"或"接口”, 而是被抽象出来的一套“类库”, 它只包含骨架代码, 真正的业务逻辑需要委派给定义中的“实现”来完成. 这里的“实现”, 也并非“接口的实现类”, 而是一套独立的”类库“. ”抽象“和”实现“独立开发, 通过对象之间的组合关系, 组装在一起.

一个例子就是Java中的JDBC与其他数据库的关系.

JDBC定义了一个通用的接口, 其他数据库实现这一套接口. 在执行数据库操作时, JDBC将数据库的操作委托给真正执行的实现类来执行.

举例

使用桥接模式来实现一套告警机制: 根据不同的告警规则, 触发不同类型的告警. 并且告警支持多种通知渠道.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 public interface MsgSender {
   void send(String message);
 }
 
 public class TelephoneMsgSender implements MsgSender {
   private List<String> telephones;
 
   public TelephoneMsgSender(List<String> telephones) {
     this.telephones = telephones;
   }
 
   @Override
   public void send(String message) {
     //...
   }
 
 }
 
 public class EmailMsgSender implements MsgSender {
   // 与TelephoneMsgSender代码结构类似,所以省略...
 }
 
 public class WechatMsgSender implements MsgSender {
   // 与TelephoneMsgSender代码结构类似,所以省略...
 }
 
 public abstract class Notification {
   protected MsgSender msgSender;
 
   public Notification(MsgSender msgSender) {
     this.msgSender = msgSender;
   }
 
   public abstract void notify(String message);
 }
 
 public class SevereNotification extends Notification {
   public SevereNotification(MsgSender msgSender) {
     super(msgSender);
   }
 
   @Override
   public void notify(String message) {
     msgSender.send(message);
   }
 }
 
 public class UrgencyNotification extends Notification {
   // 与SevereNotification代码结构类似,所以省略...
 }
 public class NormalNotification extends Notification {
   // 与SevereNotification代码结构类似,所以省略...
 }
 public class TrivialNotification extends Notification {
   // 与SevereNotification代码结构类似,所以省略...
 }

代理、桥接、装饰器、适配器4种设计模式的区别