【设计模式-中介者模式】

定义

中介者模式(Mediator Pattern)是一种行为设计模式,通过引入一个中介者对象,来降低多个对象之间的直接交互,从而减少它们之间的耦合度。中介者充当不同对象之间的协调者,使得对象之间的通信变得简单且集中。

UML图

  • Mediator(中介者接口):定义中介者与同事之间的交互方法。
  • ConcreteMediator(具体中介者):实现中介者接口,维护对同事对象的引用,并协调它们之间的交互。
  • Colleague(同事抽象类):通常持有对中介者的引用,通过中介者进行通信。
  • ConcreteColleague(同事类):具体的组件类,通常持有对中介者的引用,通过中介者进行通信。

代码

java 复制代码
// Mediator interface
interface Mediator {
    void send(String message, Colleague colleague);
}

// Concrete Mediator
class ChatMediator implements Mediator {
    private List<Colleague> colleagues = new ArrayList<>();

    public void addColleague(Colleague colleague) {
        colleagues.add(colleague);
    }

    @Override
    public void send(String message, Colleague colleague) {
        for (Colleague c : colleagues) {
            // Prevent sending message back to the sender
            if (c != colleague) {
                c.receive(message);
            }
        }
    }
}

// Colleague interface
abstract class Colleague {
    protected Mediator mediator;

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

    public abstract void send(String message);
    public abstract void receive(String message);
}

// Concrete Colleague
class User extends Colleague {
    private String name;

    public User(Mediator mediator, String name) {
        super(mediator);
        this.name = name;
    }

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

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

// Client code
public class MediatorPatternDemo {
    public static void main(String[] args) {
        ChatMediator mediator = new ChatMediator();

        User user1 = new User(mediator, "Alice");
        User user2 = new User(mediator, "Bob");

        mediator.addColleague(user1);
        mediator.addColleague(user2);

        user1.send("Hello Bob!");
        user2.send("Hi Alice!");
    }
}

优点

  • 降低耦合性:同事对象不需要直接引用彼此,减少了依赖关系。
  • 集中管理:所有的交互逻辑集中在中介者中,易于维护和修改。
  • 灵活性:可以方便地添加新的同事类或修改交互逻辑,而不需要改变其他类。

缺点

  • 中介者复杂性:中介者可能会变得复杂,尤其是当它需要处理多个同事对象时。
  • 扩展困难:添加新的同事类可能需要对中介者进行修改,从而影响系统的灵活性。

使用场景

  • 当多个对象之间的通信需要被集中控制时。
  • 当系统中存在大量同事对象,且它们之间的交互复杂时。
  • 当希望减少类之间的依赖关系,提升系统的可维护性时。
相关推荐
人月神话-Lee16 小时前
【图像处理】框架设计——协议、值类型与工程化思维
图像处理·人工智能·ios·设计模式·架构·ai编程·swift
AI大法师17 小时前
Xbox回归经典绿
大数据·设计模式·xbox
老码观察17 小时前
设计模式实战解读(六):装饰器模式——功能增强,不动原代码
java·设计模式·装饰器模式
Doris_20231 天前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_20231 天前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo1 天前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
invicinble1 天前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
invicinble2 天前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式
PersonalViolet2 天前
模板方法模式实战:重构Agent工具审批,告别重复代码
设计模式·agent