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

定义

中介者模式(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!");
    }
}

优点

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

缺点

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

使用场景

  • 当多个对象之间的通信需要被集中控制时。
  • 当系统中存在大量同事对象,且它们之间的交互复杂时。
  • 当希望减少类之间的依赖关系,提升系统的可维护性时。
相关推荐
Pkmer8 小时前
古法编程: 适配器模式
java·设计模式
灰子学技术1 天前
Envoy 使用的设计模式技术文档
设计模式
Alex艾力的IT数字空间1 天前
再思“把事情做对”与“把事情做好”的辩证关系与先后顺序
信息可视化·需求分析·学习方法·抽象工厂模式·远程工作·原型模式·中介者模式
Carl_奕然1 天前
【智能体】Agent的四种设计模式之:ReAct
人工智能·设计模式·语言模型
二哈赛车手1 天前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
楼田莉子1 天前
仿Muduo的高并发服务器:Channel模块与Poller模块
linux·服务器·c++·学习·设计模式
geovindu2 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
嵌入式学习_force2 天前
02_state
设计模式·蓝牙
qcx232 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
Cosolar3 天前
提示词工程面试题系列 - Zero-Shot Prompting 和 Few-Shot Prompting 的核心区别是什么?
人工智能·设计模式·架构