设计模式桥接模式

本文最后更新于:2024年3月18日 凌晨

设计模式桥接模式

  • 将抽象部分与它的实现部分分离,使它们都可以独立的变化,而不会直接影响到其他部分。
  • 桥接模式解决了多层继承的结构,处理多维度变化的场景,将各个维度设计成独立的继承结构,使各个维度可以独立的扩展在抽象层建立联系。
  • 优点
    • 桥接模式偶尔类似于多继承方案,但是多继承方案违背了类的单一职责原则,复用性比较差,类的个数也非常多,桥接模式是比多继承方案更好的解决方法,极大的减少了子类的个数,从而降低管理和维护的成本。
    • 桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统,符合开闭原则,就像一座桥,可以把两个变化的维度连接起来。
  • 缺点
    • 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
    • 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。
  • 使用场景
    • Java语言通过Java虚拟机实现了平台的无关性。
    • 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
57
58
59
60
61
62
63
64
65
66
public class BridgeMode {
public static void main(String[] args) {
// Apple Laptop
Computer appleLaptop= new Laptop(new Apple());
appleLaptop.info();
// Lenovo Desktop
Computer lenovoDesktop = new Desktop(new Lenovo());
lenovoDesktop.info();

}
}

class Laptop extends Computer {
public Laptop(Brand brand) {
super(brand);
}

@Override
public void info() {
super.info();
System.out.println("Laptop");
}
}


class Desktop extends Computer {
public Desktop(Brand brand) {
super(brand);
}

@Override
public void info() {
super.info();
System.out.println("Desktop");
}
}

abstract class Computer {
protected Brand brand;

public Computer(Brand brand) {
this.brand = brand;
}

public void info() {
brand.info();
}
}

class Lenovo implements Brand {
@Override
public void info() {
System.out.print("Lenovo ");
}
}

class Apple implements Brand {
@Override
public void info() {
System.out.print("Apple ");
}
}

interface Brand {
void info();
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!