设计模式-行为型模式-中介者模式

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

设计模式-行为型模式-中介者模式_第1张图片

首先,我们定义一个Colleague接口,表示同事类:
public interface Colleague {
    void send(String message, Mediator mediator);
    void receive(String message);
}
然后,我们实现几个具体的同事类
public class ConcreteColleagueA implements Colleague {
    private Mediator mediator;

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

    @Override
    public void send(String message, Mediator mediator) {
        mediator.relayMessage(this, message);
    }

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

public class ConcreteColleagueB implements Colleague {
    private Mediator mediator;

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

    @Override
    public void send(String message, Mediator mediator) {
        mediator.relay(this, message);
    }

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

接下来,我们定义Mediator接口,该接口定义了同事类与中介者之间的交互:

public interface Mediator {
    void relay(String message, Colleague colleague);
}
然后,我们实现具体的Mediator类,例如ConcreteMediator:
import java.util.HashMap;
import java.util.Map;

public class ConcreteMediator implements Mediator {
    private Map colleagues = new HashMap<>();

    public void register(Colleague colleague, String name) {
        colleagues.put(colleague, name);
    }

    public void relay(String message, Colleague colleague) {
        String colleagueName = colleagues.get(colleague);
        for (Colleague c : colleagues.keySet()) {
            if (!c.equals(colleague)) {
                c.receive(colleagueName + " says: " + message);
            }
        }
    }
}

最后,我们编写一个客户端类来测试这个中介者模式:
public class Client {
    public static void main(String[] args) {
        Mediator mediator = new ConcreteMediator();
        
        Colleague colleagueA = new ConcreteColleagueA(mediator);
        Colleague colleagueB = new ConcreteColleagueB(mediator);
        
        mediator.register(colleagueA, "A");
        mediator.register(colleagueB, "B");
        
        colleagueA.send("Hello", mediator);
        colleagueB.send("World", mediator);
    }
}

 在这个例子中,ConcreteColleagueA和ConcreteColleagueB类通过ConcreteMediator类进行通信,而不需要它们之间相互知道或持有对方的引用。这就是中介者模式的核心思想:减少类之间的直接耦合,让它们通过中介者对象进行交互。

你可能感兴趣的:(设计模式,中介者模式,java)