中介者模式(Mediator Pattern)
|
1 2 3 |
定义:用来降低多个对象和类之间的通信复杂性。 目的:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 场景:MVC框架中的控制器C就是模型M和识图V的中介者。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
// 中介者:统一协调跑道 const tower = { currentPlane: null, requestLanding(plane) { if (this.currentPlane) { console.log(`${plane.name}:跑道被占用,请等待`) return } this.currentPlane = plane plane.land() }, releaseRunway(plane) { if (this.currentPlane === plane) { this.currentPlane = null } } } // 参与者:只与塔台通信,不直接联系其他飞机 class Plane { constructor(name, tower) { this.name = name this.tower = tower } requestLanding() { this.tower.requestLanding(this) } land() { console.log(`${this.name}:开始降落`) } leaveRunway() { this.tower.releaseRunway(this) } } const planeA = new Plane('飞机A', tower) const planeB = new Plane('飞机B', tower) planeA.requestLanding() // 飞机A:开始降落 planeB.requestLanding() // 飞机B:跑道被占用,请等待 planeA.leaveRunway() planeB.requestLanding() // 飞机B:开始降落 |
Github地址:https://github.com/skillnull/Design-Mode-Example[……]