• 设计模式-中介者模式


    简介

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

    基本概念

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

    优点

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

    缺点

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

    使用场景

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

    实现示例

    假设我们有一个聊天室应用,其中多个用户(组件)通过聊天室(中介者)进行交流。以下是一个简单的 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 Best Books on Kubernetes for Beginners in 2023
    【Mysql】EXPLAIN
    "科来杯"第十届山东省大学生网络安全技能大赛决赛复现WP
    Unity 实现原神中的元素反应
    2022-安洵杯
    Day 5 C++
    Head First设计模式(阅读笔记)-02.观察者模式
    Java之集合(15个demo)
    生物信息学——常见的四种文件格式(fasta,fastq,sam,vcf)
    Python|OpenCV-图像的添加和混合操作(8)
  • 原文地址:https://blog.csdn.net/qq_34574204/article/details/139827678