java23种设计模式-中介者模式

定义

用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

角色

  • Colleague:是一个抽象类或者接口,提供和其他Colleague通讯的方法
    notify(String name)。参数name是其他Colleague的名字。
  • ColleagueA,ColleagueB: 都是Colleague的实现类。
  • Mediator: 中介者类,聚合了一系列的同事类,使得它们之间可以相互通信。具体同事类ColleagueA等都是通过Mediator,调用Mediator的notify(String name)方法向其他同事类发送消息。notify(String name)通过name找到集合中对应的Colleague并向其传递消息。Mediator类提供add(Colleague colleague)方法增加自己维护的Colleague集合中的对象。

UML

实现

/**
 * desc : 同事接口
 * Created by tiantian on 2018/9/23
 */
public interface Colleague {
    
    void notify(String name);
    
    void receive();
    
    String getName();
}
/**
 * desc : 具体同事A
 * Created by tiantian on 2018/9/23
 */
public class ColleagueA implements Colleague{

    private String name;

    public ColleagueA(String name) {
        this.name = name;
    }
    
    @Override
    public void notify(String name) {
        Mediator.notify(name);
    }

    @Override
    public void receive() {
        System.out.println("ColleagueA received message");
    }

    @Override
    public String getName() {
        return name;
    }
}
/**
 * desc : 具体同事A
 * Created by tiantian on 2018/9/23
 */
public class ColleagueB implements Colleague{
    
    private String name;

    public ColleagueB(String name) {
        this.name = name;
    }

    @Override
    public void notify(String name) {
        Mediator.notify(name);
    }

    @Override
    public void receive() {
        System.out.println("ColleagueB received message");
    }

    @Override
    public String getName() {
        return name;
    }
}
/**
 * desc : 媒介类
 * Created by tiantian on 2018/9/23
 */
public class Mediator {
    
    private static Map<String, Colleague> colleagues = new HashMap<>();
    
    public static void notify(String name) {
        Colleague colleague = colleagues.get(name);
        colleague.receive();
    }
    
    public static void add(Colleague colleague) {
        colleagues.put(colleague.getName(), colleague);
    }
}
public class Test {
    public static void main(String[] args) {
        Colleague colleagueA = new ColleagueA("colleagueA");
        Colleague colleagueB = new ColleagueB("colleagueB");
        Mediator.add(colleagueA);
        Mediator.add(colleagueB);
        
        colleagueA.notify("colleagueB");
    }
}

总结

中介者模式使得对象之间网状的依赖关系变成星型依赖关系。对象之间通信时不必显式的相互调用,而是通过中介者间接的传递消息。这种依赖关系也符合迪米特原则。该模式缺点是,当需要互相通信的同事类数量很多的时候,中介者的复杂度将变的很高,维护难度也随之增加。

猜你喜欢

转载自blog.csdn.net/m0_37577221/article/details/82828981