介绍
中介者模式:用一个中介对象封装一些列的对象交互,解除对象与对象之间的耦合关系。
这个像我们平时租房子,我们去找中介就行,省去了跟房东交涉的麻烦。有点不太恰当,意思差不多吧。
实现
function Player(name) {
this.name = name
this.enemy = null
}
Player.prototype.win = function () {
console.log(this.name + ' won')
}
Player.prototype.lose = function () {
console.log(this.name + ' lose')
}
Player.prototype.die = function () {
this.lose()
this.enemy.win()
}
const player1 = new Player('皮卡')
const player2 = new Player('球')
player1.enemy = player2
player2.enemy = player1
player1.die()
小结
中介者模式的优点是减少对象之间的耦合,相应的这样会增加中介者对象的复杂性。