设计模式-中介者模式

简介

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

基本概念

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

优点

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

缺点

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

使用场景

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

实现示例

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

相关推荐
子兮曰6 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭6 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路8 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒10 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol11 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉11 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau11 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生11 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼11 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君8799711 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter