设计模式-中介者模式

简介

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

基本概念

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

优点

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

缺点

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

使用场景

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

实现示例

假设我们有一个聊天室应用,其中多个用户(组件)通过聊天室(中介者)进行交流。以下是一个简单的 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 中,使得每个参与者的实现更简单,也更容易管理和扩展。

相关推荐
计算机魔术师1 小时前
美国司法部正式站队 OpenAI,AI 训练的版权账要这么算了
前端
IT_陈寒1 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
风骏时光牛马1 小时前
疑难Bug根因定位与问题复盘分析
前端
创新技术阁2 小时前
FastapiAdmin 系统日志体系与核心配置参数详解
前端·后端·fastapi
掘金酱2 小时前
【社区公告】签到与矿石奖励解耦说明
前端
promiseThen2 小时前
LWC Workflow:用 7 个 Cursor Skill 搭一条 AI 协作开发流水线
前端·ai编程
一个游离的指针3 小时前
函数管道:消除深度嵌套调用
前端·javascript
浅诺3 小时前
Nginx sub_filter 的“幽灵陷阱”:为什么页面能打开,懒加载的 JS 却全是 404?
前端
PBitW3 小时前
为什么vite中TS报错,可以继续运行?Webpack不行?
前端·webpack·typescript·vite
光影少年3 小时前
react navite手写 FlatList 优化配置
前端·react native·react.js