什么是中介者模式

中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。

面向对象例子:

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class Player{
constructor(name, teamColor, playerDirector) {
this.name = name;
this.teamColor = teamColor;
this.status = 'live';
this.playerDirector = playerDirector;
this.add();
}

win() {
console.log('for self win action: ' + this.name);
}

lose() {
console.log('for self lose action: ' + this.name);
}

add() {
console.log('for self add action: ' + this.name);
this.playerDirector.recieveMessage('add', this);
}

remove() {
console.log('for self remove action: ' + this.name);
this.playerDirector.recieveMessage('remove', this);
}

die() {
console.log('for self die action: ' + this.name);
this.playerDirector.recieveMessage('die', this);
}

getMessage(message) {
console.log(`${this.name} recieved message: ${message}`);
}
}

export class PlayerMediator{
constructor() {
this.players = {};
}

recieveMessage(type, player) {
this[type](player);
}

add(player) {
this.players[player.teamColor] = this.players[player.teamColor] || [];
this.players[player.teamColor].push(player);
this.getAllPlayerExceptThis(player).forEach((p) => {
p.getMessage(`player ${player.name} added.`);
});
}

remove(player) {
let index = this.players[player.teamColor].indexOf(player);
this.players[player.teamColor][index].status = 'disconnect';
this.getAllPlayerExceptThis(player).forEach((p) => {
p.getMessage(`player ${player.name} disconnected.`);
});
if (this.verifyOver(player.teamColor)) {
this.gameOver(player.teamColor)
}
}

die(player) {
let index = this.players[player.teamColor].indexOf(player);
this.players[player.teamColor][index].status = 'die';
this.getAllPlayerExceptThis(player).forEach((p) => {
p.getMessage(`player ${player.name} dead.`);
});
if (this.verifyOver(player.teamColor)) {
this.gameOver(player.teamColor)
}
}

getAllPlayerExceptThis(player) {
let ret = [];
for (let t of Object.keys(this.players)) {
for (let p of this.players[t]) {
if (player !== p) {
ret.push(p);
}
}
}
return ret;
}

verifyOver(teamColor) {
for (let player of this.players[teamColor]) {
if (player.status === 'live') {
return false;
}
}
return true
}

gameOver(teamColor) {
for (let t of Object.keys(this.players)) {
for (let player of this.players[t]) {
if (teamColor === player.teamColor) {
player.lose();
} else {
player.win();
}
}
}
}
}