定义
当一个系统中对象之间的关系呈下图所示的网状结构的关系时,一个对象会影响到其他对象,同时也会受到其他对象的影响。这将会导致一个过渡耦合的系统。

中介者模式即是使用一个中介对象,来封装一系列对象的交互,中介者使各对象不需要显示的相互引用,从而使其耦合松散。

实现
以一个简单的聊天室来实现中介者模式。
实例中,多个用户可以向聊天室发送信息,聊天室向所有用户显示消息。
// 聊天室类
class CharRoom {
static showMessage(name: string, message: string) {
console.log(`${name}:${message}`)
}
}
// 抽象
abstract class User {
protected name: string
public abstract sendMessage(message: string): void
}
class Jock extends User {
constructor () {
super()
this.name = 'Jock'
}
public sendMessage (message: string): void {
CharRoom.showMessage(this.name, message)
}
}
class Mary extends User {
constructor () {
super()
this.name = 'Mary'
}
public sendMessage (message: string): void {
CharRoom.showMessage(this.name, message)
}
}
const mary = new Mary()
const jock = new Jock()
mary.sendMessage('Hello world!')
jock.sendMessage('Hello Vue')
使用场景
系统中村子啊比较复杂的引用关系,导致结构层网状,混乱,且难以复用。
优缺点
优点:
- 各个类之间解耦
- 降低类复杂度
缺点:
中介者会庞大,变得难以维护。