中介者模式是一种行为型设计模式,它允许将复杂的系统划分为一组相互关联的对象中介者,这些对象通过中介者对象进行通信,而不是直接相互引用。中介者模式可以减少对象之间的耦合度,使得系统更易于维护和扩展。在中介者模式中中介者中介者对象负责协调对象之间的交互,它通常包含一个或多个接口,用于定义对象之间的通信协议。当一个对象需要与其他对象进行通信时,它将消息发送给中介者对象,中介者对象将消息转发给目标对象,从而实现对象之间的通信。中介者模式适用于需要协调多个对象之间的复杂交互的场景,例如图形用户界面(GUI)应用程序、多人在线游戏等。

优点:

减少类之间的耦合,将原本互相依赖的类通过中介者进行通信,使得类之间的关系更加简单明了。可以将控制集中管理,降低系统的复杂度。可以减少子类的生成,因为中介者将原本分散在多个类中的行为集中在一起,减少了子类的生成。

缺点:

中介者本身可能会变得复杂,难以维护。中介者模式可能会导致系统变得过于集中化,使得系统的灵活性降低。

引用场景:

当系统中多个对象之间存在复杂的交互关系,且这些关系难以维护时,可以考虑使用中介者模式。当系统中的对象之间存在循环依赖关系时,可以使用中介者模式来解决这个问题。当系统需要对某些对象进行集中控制时,可以使用中介者模式。

中介者模式的实现方法包括以下几个步骤:

定义中介者接口:中介者接口定义了中介者需要实现的方法,这些方法用于与其他对象进行通信。实现中介者类:中介者类实现了中介者接口,负责协调其他对象之间的交互。定义对象接口:对象接口定义了对象需要实现的方法,这些方法用于与中介者进行通信。实现对象类:对象类实现了对象接口,负责与中介者进行通信,并根据中介者的指示执行相应的操作。在对象类中保存中介者对象:对象类需要保存中介者对象的引用,以便能够与中介者进行通信。在客户端代码中创建中介者对象和对象对象:客户端代码需要创建中介者对象和对象对象,并将对象对象的中介者引用设置为中介者对象。

// Step 1: 定义中介者接口
class Mediator {
  send(message, colleague) {}
}
// Step 2: 实现中介者类
class ConcreteMediator extends Mediator {
  constructor() {
    super();
    this.colleague1 = null;
    this.colleague2 = null;
  }
  set colleague1(value) {
    this._colleague1 = value;
  }
  set colleague2(value) {
    this._colleague2 = value;
  }
  send(message, colleague) {
    if (colleague === this._colleague1) {
      this._colleague2.notify(message);
    } else {
      this._colleague1.notify(message);
    }
  }
}
// Step 3:  定义对象接口
class Colleague {
  constructor(mediator) {
    this._mediator = mediator;
  }
  send(message) {}
  notify(message) {}
}
// Step 4: 实现对象类
class ConcreteColleague1 extends Colleague {
  constructor(mediator) {
    super(mediator);
  }
  send(message) {
    this._mediator.send(message, this);
  }
  notify(message) {
    console.log(`Colleague 1 received message: ${message}`);
  }
}
class ConcreteColleague2 extends Colleague {
  constructor(mediator) {
    super(mediator);
  }
  send(message) {
    this._mediator.send(message, this);
  }
  notify(message) {
    console.log(`Colleague 2 received message: ${message}`);
  }
}
// Step 5: 在对象类中保存中介者对象
const mediator = new ConcreteMediator();
const colleague1 = new ConcreteColleague1(mediator);
const colleague2 = new ConcreteColleague2(mediator);
mediator.colleague1 = colleague1;
mediator.colleague2 = colleague2;
// Step 6: 在客户端代码中创建中介者对象和对象对象
colleague1.send('Hello, colleague 2!');
colleague2.send('Hi, colleague 1!');
//运行结果
Colleague 2 received message: Hello, colleague 2!
 Colleague 1 received message: Hi, colleague 1!


限时特惠:
本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情

站长微信:Jiucxh

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注