Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript设计模式(十一):中介者模式 #33

Open
yangrenmu opened this issue Sep 22, 2020 · 0 comments
Open

JavaScript设计模式(十一):中介者模式 #33

yangrenmu opened this issue Sep 22, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

介绍

中介者模式:用一个中介对象封装一些列的对象交互,解除对象与对象之间的耦合关系。

这个像我们平时租房子,我们去找中介就行,省去了跟房东交涉的麻烦。有点不太恰当,意思差不多吧。

实现

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()

小结

中介者模式的优点是减少对象之间的耦合,相应的这样会增加中介者对象的复杂性。

@yangrenmu yangrenmu added the mode label Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant