设计模式教程:中介者模式(Mediator Pattern)

news/2025/2/22 17:42:04

中介者模式是一种行为型设计模式,它用于减少对象之间的直接依赖关系。通过引入一个中介者对象,所有对象的交互都通过中介者进行,而不是直接相互通信。这种模式的主要目的是减少对象之间的耦合,提升系统的灵活性和可维护性。

1. 定义和意图

意图中介者模式通过一个中介者对象来协调和控制多个对象之间的交互,从而减少多个对象之间的直接联系,降低系统的复杂度。对象通过中介者进行通信,而不直接依赖于彼此。

2. 组成部分

中介者模式通常由以下几个角色组成:

  • Mediator(中介者接口):声明了一个方法,用于同事对象之间的通信。
  • ConcreteMediator(具体中介者):实现中介者接口,负责协调同事对象之间的交互。
  • Colleague(同事类):定义同事对象,所有对象与中介者的交互都通过中介者进行。
  • ConcreteColleague(具体同事类):继承自同事类,能够通过中介者与其他对象进行交互。

3. 结构图

                +---------------------+
                |    Mediator         |
                +---------------------+
                | + notify()          |
                +---------------------+
                        ^
                        |
            +---------------------------+
            | ConcreteMediator           |
            +---------------------------+
            | + colleague1: Colleague1   |
            | + colleague2: Colleague2   |
            +---------------------------+
                        |
        +--------------------------+------------------+
        |                                              |
+---------------+                             +------------------+
| Colleague1    |                             | Colleague2       |
+---------------+                             +------------------+
| + setMediator()|                             | + setMediator()  |
| + action()     |                             | + action()       |
+---------------+                             +------------------+

4. 代码实现

4.1 中介者接口

首先,定义中介者接口,声明同事对象交互的方法。

// 中介者接口
public interface Mediator {
    void notify(Colleague colleague, String message);
}
4.2 具体中介者

然后,定义一个具体的中介者类,负责协调各个同事对象之间的交互。

// 具体中介者
public class ConcreteMediator implements Mediator {
    private Colleague1 colleague1;
    private Colleague2 colleague2;

    // 设置同事对象
    public void setColleague1(Colleague1 colleague1) {
        this.colleague1 = colleague1;
    }

    public void setColleague2(Colleague2 colleague2) {
        this.colleague2 = colleague2;
    }

    @Override
    public void notify(Colleague colleague, String message) {
        if (colleague == colleague1) {
            // 如果是colleague1,通知colleague2
            colleague2.receive(message);
        } else {
            // 如果是colleague2,通知colleague1
            colleague1.receive(message);
        }
    }
}
4.3 同事类

接下来,定义一个同事类的接口,所有同事类都必须实现这个接口。

// 同事类接口
public abstract class Colleague {
    protected Mediator mediator;

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }

    // 设置中介者
    public void setMediator(Mediator mediator) {
        this.mediator = mediator;
    }

    // 接收消息
    public abstract void receive(String message);

    // 发送消息
    public abstract void send(String message);
}
4.4 具体同事类

然后,定义具体的同事类,负责执行具体的操作。

// 具体同事类1
public class Colleague1 extends Colleague {

    public Colleague1(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void receive(String message) {
        System.out.println("Colleague1 received: " + message);
    }

    @Override
    public void send(String message) {
        System.out.println("Colleague1 sends: " + message);
        mediator.notify(this, message);
    }
}

// 具体同事类2
public class Colleague2 extends Colleague {

    public Colleague2(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void receive(String message) {
        System.out.println("Colleague2 received: " + message);
    }

    @Override
    public void send(String message) {
        System.out.println("Colleague2 sends: " + message);
        mediator.notify(this, message);
    }
}
4.5 使用示例

最后,创建一个应用程序来使用中介者模式

public class Main {
    public static void main(String[] args) {
        // 创建中介者对象
        ConcreteMediator mediator = new ConcreteMediator();

        // 创建具体同事对象
        Colleague1 colleague1 = new Colleague1(mediator);
        Colleague2 colleague2 = new Colleague2(mediator);

        // 设置同事对象
        mediator.setColleague1(colleague1);
        mediator.setColleague2(colleague2);

        // 发送消息
        colleague1.send("Hello from Colleague1!");
        colleague2.send("Hello from Colleague2!");
    }
}

4.6 输出结果

Colleague1 sends: Hello from Colleague1!
Colleague2 received: Hello from Colleague1
Colleague2 sends: Hello from Colleague2!
Colleague1 received: Hello from Colleague2

5. 优点

  • 减少类之间的依赖:通过中介者模式,同事类不再直接引用彼此,而是通过中介者对象进行通信,从而减少了类之间的耦合。
  • 集中化通信逻辑:中介者将交互的逻辑集中在一个地方,便于维护和扩展。
  • 扩展性强:如果添加新的同事类,只需要在中介者中进行适配,而不需要修改现有的类。

6. 缺点

  • 中介者的复杂性:当系统中存在大量同事对象时,中介者对象的职责会变得非常复杂,可能会导致中介者本身的代码膨胀。
  • 过度集中:如果所有的交互都通过中介者,可能会导致中介者对象成为“上帝对象”,承担过多的职责,变得难以维护。

7. 应用场景

中介者模式适用于以下情况:

  • 复杂的对象交互:当多个对象之间有复杂的交互关系时,使用中介者模式能够简化这些交互,避免直接依赖。
  • 解耦合:如果对象之间需要进行频繁的交互,但又不希望它们之间过于紧密地耦合,可以通过中介者来解耦。
  • 多个对象的通信协调:适用于需要协调多个对象行为的场景,比如 UI 界面中多个控件之间的交互。

8. 总结

中介者模式通过将对象间的交互集中到一个中介者对象中,降低了对象之间的耦合度,简化了对象间的通信逻辑。它使得系统更容易维护和扩展,但也可能导致中介者过于复杂,成为系统的瓶颈。因此,在使用中介者模式时,需要权衡其优缺点,根据具体的需求来选择是否使用。

版权声明
  1. 本文内容属于原创,欢迎转载,但请务必注明出处和作者,尊重原创版权。
  2. 转载时,请附带原文链接并注明“本文作者:扣丁梦想家
  3. 禁止未经授权的商业转载。

如果您有任何问题或建议,欢迎留言讨论。


http://www.niftyadmin.cn/n/5862590.html

相关文章

深入浅出机器学习:概念、算法与实践

目录 引言 机器学习的基本概念 什么是机器学习 机器学习的基本要素 机器学习的主要类型 监督学习(Supervised Learning) 无监督学习(Unsupervised Learning) 强化学习(Reinforcement Learning) 机器…

批量操作实现与优化

1、批量操作 方案设计 基本功能实现 /*** 批量添加题目和题库关联** param questionIdList 题目id列表* param questionBankId 题库id* param loginUser 登录用户*/OverrideTransactional(rollbackFor Exception.class)public void batchAddQuestionBankQuestion(List<Lon…

从0开始的操作系统手搓教程9:更好的内核1——简单讨论一下C与ASM的混合编程

现在&#xff0c;我们已经成功的进入了我们的内核。在之后更长的一段时间&#xff0c;我们可以使用更加高级的编程语言&#xff0c;也就是我们的C语言&#xff0c;而不是汇编来完成我们的工作。 C语言的确被广泛认为是一门非常接近硬件的编程语言&#xff0c;但是&#xff0c;…

【Excel】【VBA】根据内容调整打印区域

Excel VBA&#xff1a;自动调整打印区域的实用代码解析 在Excel中&#xff0c;我们经常需要调整打印区域。今天介绍一段VBA代码&#xff0c;它可以根据C列的内容自动调整打印区域。 Dim ws As Worksheet Dim lastRow As Long Dim r As Long 设置当前工作表 Set ws ActiveSh…

【目标检测】【YOLOv4】YOLOv4:目标检测的最佳速度与精度

YOLOv4&#xff1a;目标检测的最佳速度与精度 0.论文摘要 有许多特征被认为可以提高卷积神经网络&#xff08;CNN&#xff09;的准确性。需要在大规模数据集上对这些特征的组合进行实际测试&#xff0c;并对结果进行理论上的验证。某些特征仅适用于特定模型和特定问题&#…

网络安全入门持续学习与进阶路径(一)

职业认证与实战进阶 1 考取核心安全认证 认证名称适合人群考试要求考试时间/费用核心价值注意点CEH&#xff08;道德黑客认证&#xff09;渗透测试方向&#xff0c;入门级无强制经验要求&#xff0c;需参加官方培训&#xff08;或自学&#xff09;4小时&#xff0c;125题&…

基于云的物联网系统用于实时有害藻华监测:通过MQTT和REST API无缝集成ThingsBoard

论文标题 **英文标题&#xff1a;**Cloud-Based IoT System for Real-Time Harmful Algal Bloom Monitoring: Seamless ThingsBoard Integration via MQTT and REST API **中文标题&#xff1a;**基于云的物联网系统用于实时有害藻华监测&#xff1a;通过MQTT和REST API无缝集…

深度学习笔记16-VGG-16算法-Pytorch实现人脸识别

目录 前言 一、 前期准备 1. 设置GPU 2. 导入数据 3. 划分数据集 二、调用官方的VGG-16模型 三、 训练模型 1. 编写训练函数 2. 编写测试函数 3. 设置动态学习率 4. 正式训练 四、 结果可视化 1. Loss与Accuracy图 2. 指定图片进行预测 3. 模型评估 五、总结 前言 &#x1f368…