-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMediator-Pattern.js
More file actions
52 lines (40 loc) · 1.09 KB
/
Copy pathMediator-Pattern.js
File metadata and controls
52 lines (40 loc) · 1.09 KB
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
// 中介者模式(Mediator Pattern)
// 中介者:统一协调跑道
const tower = {
currentPlane: null,
requestLanding(plane) {
if (this.currentPlane) {
console.log(`${plane.name}:跑道被占用,请等待`)
return
}
this.currentPlane = plane
plane.land()
},
releaseRunway(plane) {
if (this.currentPlane === plane) {
this.currentPlane = null
}
}
}
// 参与者:只与塔台通信,不直接联系其他飞机
class Plane {
constructor(name, tower) {
this.name = name
this.tower = tower
}
requestLanding() {
this.tower.requestLanding(this)
}
land() {
console.log(`${this.name}:开始降落`)
}
leaveRunway() {
this.tower.releaseRunway(this)
}
}
const planeA = new Plane('飞机A', tower)
const planeB = new Plane('飞机B', tower)
planeA.requestLanding() // 飞机A:开始降落
planeB.requestLanding() // 飞机B:跑道被占用,请等待
planeA.leaveRunway()
planeB.requestLanding() // 飞机B:开始降落