设计模式-中介者模式

简介

中介者模式是一种行为设计模式,它允许我们减少多个组件(对象)之间的直接通信,而是通过一个中介者对象来协调相互作用。这种模式有助于减少组件之间的依赖关系,使其更容易维护和扩展

基本概念

在中介者模式中,组件(通常称为同事类)不直接与其他组件通信。相反,它们通过中介者对象进行交互。这种设置有助于将组件之间的通信逻辑集中在一个位置,使得代码更加整洁并且易于理解和维护

优点

  • 降低耦合度:组件不需要知道其他组件的详细信息,只需与中介者沟通。
  • 集中控制交互:所有的组件交互都通过同一个中介者,方便进行监控和控制。
  • 更易于维护和修改:添加新的交互或修改现有逻辑只需更改中介者代码,而不是多个组件。

缺点

  • 中介者可能变得复杂:随着系统的扩展,中介者自身可能会变得过于复杂,成为一个难以维护的大型类。
  • 可能影响性能:所有的通信都通过中介者,可能会导致性能瓶颈。

使用场景

  • 当多个组件相互交互,但交互方式非常复杂时,使用中介者可以简化这些组件之间的通信。
  • 当你想要在不同组件之间的交互中引入新的行为,而不影响这些组件的时候

实现示例

假设我们有一个聊天室应用,其中多个用户(组件)通过聊天室(中介者)进行交流。以下是一个简单的 JavaScript 实现:

javascript 复制代码
class ChatRoom {
  constructor() {
    this.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);
        }
      }
    }
  }
}

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}`);
  }
}

// 使用示例
const chatroom = new ChatRoom();

const alice = new Participant("Alice");
const bob = new Participant("Bob");
const charlie = new Participant("Charlie");

chatroom.register(alice);
chatroom.register(bob);
chatroom.register(charlie);

alice.send("Hi Bob!", bob);
bob.send("Hey Alice!", alice);
charlie.send("Hello everyone!");

总结

在这个示例中,ChatRoom 是中介者,负责处理所有的消息发送逻辑。Participant 类代表各个组件,它们通过 ChatRoom 进行通信。这样,参与者之间的通信逻辑就被集中到了 ChatRoom 中,使得每个参与者的实现更简单,也更容易管理和扩展。

相关推荐
im_AMBER2 小时前
告别“玄学”UI:从“删代码碰运气”到“控制 BFC 结界”
前端·css
千寻girling2 小时前
《 MongoDB 教程 》—— 不可多得的 MongoDB
前端·后端·面试
攀登的牵牛花2 小时前
前端向架构突围系列 - 状态数据设计 [8 - 3]:服务端状态与客户端状态的架构分离
前端
掘金安东尼2 小时前
⏰前端周刊第 452 期(2026年2月2日-2月8日)
前端·javascript·github
古茗前端团队2 小时前
业务方上压力了,前端仔速通RGB转CMYK
前端
广州华水科技2 小时前
单北斗变形监测一体机在基础设施安全与地质灾害监测中的应用价值分析
前端
Dragon Wu2 小时前
Electron Forge集成React Typescript完整步骤
前端·javascript·react.js·typescript·electron·reactjs
芳草萋萋鹦鹉洲哦2 小时前
【Tailwind】动画解读:Tailwind CSS Animation Examples
前端·css
华仔啊2 小时前
jQuery 4.0 发布,IE 终于被放弃了
前端·javascript
一心赚狗粮的宇叔2 小时前
03.Node.js依赖包补充说明及React&Node.Js项目
前端·react.js·node.js