【热度文章】Java设计模式之中介者模 式

ava 中的中介者模式

中介者模式(Mediator Pattern)是一种行为型设计模式,它通过一个中介对象来封装一系列对象之间的交互,使这些对象之间不需要显式地相互引用,从而降低了对象之间的耦合度。

中介者模式的主要角色:

Mediator(中介者接口或抽象类):定义了中介者与各个同事对象交互的方法。

ConcreteMediator(具体中介者):实现中介者接口,协调各个同事对象之间的交互。

Colleague(同事类接口或抽象类):定义同事对象的公共方法。

ConcreteColleague(具体同事类):实现同事类接口,每个具体同事类只知道自己的行为,而不知道其他同事类的情况,但它们都通过中介者对象来与其他同事类交互。

中介者模式的优点:

减少了各个同事类之间的相互依赖,使得系统更易于维护和扩展。

集中控制交互逻辑,使得交互逻辑的修改更加方便。

中介者模式的缺点:

中介者类可能会变得复杂,承担过多的责任。

新的同事类加入系统可能会比较困难,因为需要修改中介者类。

示例代码:

java 复制代码
interface Mediator {
    void notifyColleagues();
}

class ConcreteMediator implements Mediator {
    private ConcreteColleague1 colleague1;
    private ConcreteColleague2 colleague2;

    public ConcreteMediator(ConcreteColleague1 colleague1, ConcreteColleague2 colleague2) {
        this.colleague1 = colleague1;
        this.colleague2 = colleague2;
    }

    @Override
    public void notifyColleagues() {
        colleague1.action();
        colleague2.action();
    }
}

interface Colleague {
    void action();
}

class ConcreteColleague1 implements Colleague {
    private Mediator mediator;

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

    @Override
    public void action() {
        System.out.println("ConcreteColleague1 执行操作");
    }
}

class ConcreteColleague2 implements Colleague {
    private Mediator mediator;

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

    @Override
    public void action() {
        System.out.println("ConcreteColleague2 执行操作");
    }
}

public class MediatorPatternExample {
    public static void main(String[] args) {
        Mediator mediator = new ConcreteMediator(new ConcreteColleague1(mediator), new ConcreteColleague2(mediator));
        mediator.notifyColleagues();
    }
}

在上述示例中,ConcreteMediator作为中介者协调ConcreteColleague1和ConcreteColleague2的操作。

中介者模式适用于多个对象之间复杂的交互关系,需要集中管理这些交互的场景。

相关推荐
敲代码的 蜡笔小新5 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
周努力.3 天前
设计模式之中介者模式
设计模式·中介者模式
Cuit小唐3 天前
C++ 中介者模式详解
中介者模式
碎梦归途15 天前
23种设计模式-行为型模式之中介者模式(Java版本)
java·jvm·设计模式·中介者模式·软件设计师
程序员JerrySUN16 天前
设计模式每日硬核训练 Day 17:中介者模式(Mediator Pattern)完整讲解与实战应用
microsoft·设计模式·中介者模式
CHQIUU18 天前
Java 设计模式心法之第25篇 - 中介者 (Mediator) - 用“中央协调”降低对象间耦合度
java·设计模式·中介者模式
Pasregret21 天前
中介者模式:解耦对象间复杂交互的设计模式
设计模式·交互·中介者模式
听闻风很好吃1 个月前
Java设计模式之中介者模式:从入门到架构级实践
java·设计模式·中介者模式
搞不懂语言的程序员1 个月前
中介者模式详解及真实场景解决方案
设计模式·中介者模式