如图,左边的这种相互的沟通会非常出杂乱,复杂。严重不符合开放封闭原则,其中一个对象改了,就牵扯到很多的对象。右边的,如果一个对象改了,只要改中介者就行
// 中介者 class Mediator { constructor(a, b) { this.a = a; this.b = b; } setA() { let number = this.b.number; this.a.setNumber(number * 100); } setB() { let number = this.a.number; this.b.setNumber(number / 100); } } class A { constructor() { this.number = 0; } setNumber(num, m) { this.number = num; if (m) { m.setB(); } } } class B { constructor() { this.number = 0; } setNumber(num, m) { this.number = num; if (m) { m.setA(); } } } // 测试 let a = new A(); let b = new B(); let m = new Mediator(a, b); a.setNumber(100, m); console.log(a.number, b.number); b.setNumber(100, m); console.log(a.number, b.number);