结构型-桥接模式

概念

Bridge Pattern:将抽象部分与它的实现部分分离,使他们都可以独立地变化。

img

使用

比如提取多个底层功能模块,如运动、着色、说话模块,球类有运动和着色模块,人类有运动和说话模块,实现模块的快速组合,将实现和抽象分离,提高创建对象的灵活性

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
class Speed { // 运动模块
constructor(x, y) {
this.x = x;
this.y = y;
}
run() {
console.log(`运动起来 ${this.x} + ${this.y}`)
}
}

class Color { // 着色模块
constructor(cl) {
this.color = cl;
}
draw() {
console.log(`绘制颜色 ${this.color}` )
}
}

class Speak { // 说话模块
constructor(wd) {
this.word = wd;
}
say() {
console.log(`说话 ${this.word}` )
}
}

class Ball { // 创建球类,可以着色和运动
constructor(x, y, cl) {
this.speed = new Speed(x, y)
this.color = new Color(cl)
}
init() {
this.speed.run()
this.color.draw()
}
}

class Man { // 创建人类,可以运动和说话
constructor(x, y, wd) {
this.speed = new Speed(x, y)
this.speak = new Speak(wd)
}
init() {
this.speed.run()
this.speak.say()
}
}

const man = new Man(1, 2, 'zw')
const ball = new Ball(1, 2, '#333333')
man.init() // 运动起来 1 + 2 说话 zw
ball.init() // 运动起来 1 + 2 绘制颜色 #333333

优点

  • 扩展性好,符合开闭原则
  • 将抽象与实现分离,二者可以独立变化

缺点

  • 在设计前,需要识别出两个独立变化的维度