📅  最后修改于: 2023-12-03 15:12:08.626000             🧑  作者: Mango
中介模式是一种行为型设计模式,它提供了一个对象,该对象封装了一组对象间的交互方式,从而使各对象间的耦合度降低。
中介模式将各个对象的交互逻辑封装到中介对象中,从而使各个对象只需要与中介对象进行通信,而不需要了解其他对象的存在。
具体代码实现请参考下方的示例:
// 中介者接口
interface Mediator {
void sendMessage(String message, Colleague colleague);
}
// 具体中介者
class ConcreteMediator implements Mediator {
private Colleague colleagueA;
private Colleague colleagueB;
public void setColleagueA(Colleague colleagueA) {
this.colleagueA = colleagueA;
}
public void setColleagueB(Colleague colleagueB) {
this.colleagueB = colleagueB;
}
@Override
public void sendMessage(String message, Colleague colleague) {
if (colleague == colleagueA) {
colleagueB.receiveMessage(message);
} else if (colleague == colleagueB) {
colleagueA.receiveMessage(message);
}
}
}
// 同事接口
interface Colleague {
void receiveMessage(String message);
}
// 具体同事A
class ConcreteColleagueA implements Colleague {
private Mediator mediator;
public ConcreteColleagueA(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void receiveMessage(String message) {
System.out.println("Concrete Colleague A received message: " + message);
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
}
// 具体同事B
class ConcreteColleagueB implements Colleague {
private Mediator mediator;
public ConcreteColleagueB(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void receiveMessage(String message) {
System.out.println("Concrete Colleague B received message: " + message);
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
}
// 测试代码
public class MediatorPatternDemo {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
Colleague colleagueA = new ConcreteColleagueA(mediator);
Colleague colleagueB = new ConcreteColleagueB(mediator);
((ConcreteMediator) mediator).setColleagueA(colleagueA);
((ConcreteMediator) mediator).setColleagueB(colleagueB);
colleagueA.sendMessage("Hello, colleague B!");
colleagueB.sendMessage("Hi, colleague A!");
}
}
中介者模式适用于大型的对象交互系统,它可以解决各对象之间交互复杂、耦合度过高等问题,从而降低系统的复杂度和维护难度。在实际开发中,可以根据具体的业务场景选择是否采用中介模式。