zhangdizhangdi

中介者模式 📖

定义

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

实现

js
class Participant {
  constructor(name) {
    this.name = name
    this.chatroom = null
  }
  send(message, to) {
    this.chatroom.send(message, this, to)
  }
  receive(message, from) {
    console.log(from.name + ' to ' + this.name + ': ' + message)
  }
}

class Chatroom {
  participants = {}

  register(participant) {
    this.participants[participant.name] = participant
    participant.chatroom = this
  }

  send(message, from, to) {
    if (to) {
      to.receive(message, from)
    } else {
      for (let key in this.participants) {
        if (this.participants[key] !== from) {
          this.participants[key].receive(message, from)
        }
      }
    }
  }
}

const yoko = new Participant('Yoko')
const john = new Participant('John')
const paul = new Participant('Paul')
const ringo = new Participant('Ringo')

const chatroom = new Chatroom()
chatroom.register(yoko)
chatroom.register(john)
chatroom.register(paul)
chatroom.register(ringo)

yoko.send('All you need is love.')
yoko.send('I love you John.')
john.send('Hey, no need to broadcast', yoko)
paul.send('Ha, I heard that!')
ringo.send('Paul, what do you think?', paul)
执行结果
Yoko to John: All you need is love.
Yoko to Paul: All you need is love.
Yoko to Ringo: All you need is love.
Yoko to John: I love you John.
Yoko to Paul: I love you John.
Yoko to Ringo: I love you John.
John to Yoko: Hey, no need to broadcast
Paul to Yoko: Ha, I heard that!
Paul to John: Ha, I heard that!
Paul to Ringo: Ha, I heard that!
Ringo to Paul: Paul, what do you think?

参考