【热度文章】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的操作。

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

相关推荐
仙魁XAN4 天前
Unity 设计模式 之 行为型模式 -【中介者模式】【迭代器模式】【解释器模式】
设计模式·迭代器模式·解释器模式·中介者模式
LB_bei4 天前
设计模式-行为型模式-中介者模式
设计模式·中介者模式
coffee_baby8 天前
化繁为简:中介者模式如何管理复杂对象交互
java·spring boot·microsoft·交互·中介者模式
星光技术人15 天前
设计模式---中介者模式
设计模式·中介者模式
程序员与背包客_CoderZ18 天前
C++设计模式——Mediator中介者模式
c语言·开发语言·c++·设计模式·中介者模式
惜.己1 个月前
设计模式之中介者模式
java·设计模式·intellij-idea·idea·中介者模式
WineMonk1 个月前
设计模式 17 中介者模式
设计模式·中介者模式
程序员不想敲代码啊1 个月前
【java设计模式之中介者模式】
中介者模式
DEv C++不算C++1 个月前
Java设计模式原则及中介者模式研究
中介者模式