中介者模式是一种行为型设计模式,它的主要目的是减少多个对象之间的直接通信,并通过一个中介者对象来协调它们之间的交互。这样可以降低系统的复杂性,增加可维护性和灵活性。
示例代码
// 中介者接口
interface Mediator {
void sendMessage(String message, Colleague colleague);
}
// 抽象同事类
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void sendMessage(String message);
public abstract void receiveMessage(String message);
}
// 具体同事类A
class ConcreteColleagueA extends Colleague {
public ConcreteColleagueA(Mediator mediator) {
super(mediator);
}
@Override
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
@Override
public void receiveMessage(String message) {
System.out.println("ConcreteColleagueA received message: " + message);
}
}
// 具体同事类B
class ConcreteColleagueB extends Colleague {
public ConcreteColleagueB(Mediator mediator) {
super(mediator);
}
@Override
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
@Override
public void receiveMessage(String message) {
System.out.println("ConcreteColleagueB received message: " + message);
}
}
// 具体中介者类
class ConcreteMediator implements Mediator {
private ConcreteColleagueA colleagueA;
private ConcreteColleagueB colleagueB;
public void setColleagueA(ConcreteColleagueA colleagueA) {
this.colleagueA = colleagueA;
}
public void setColleagueB(ConcreteColleagueB 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);
}
}
}
// 测试代码
public class MediatorPatternDemo {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleagueA colleagueA = new ConcreteColleagueA(mediator);
ConcreteColleagueB colleagueB = new ConcreteColleagueB(mediator);
mediator.setColleagueA(colleagueA);
mediator.setColleagueB(colleagueB);
colleagueA.sendMessage("Hello, I am A.");
colleagueB.sendMessage("Hi, I am B.");
}
}
Mediator
接口定义了一个方法sendMessage,用于同事之间的通信。Colleague
抽象类表示同事类,其中sendMessage方法用于向中介者发送消息,receiveMessage方法用于接收来自中介者的消息。ConcreteColleagueA
和ConcreteColleagueB
是具体的同事类,它们实现了Colleague类,并重写了其抽象方法。ConcreteMediator
是具体的中介者类,它实现了Mediator接口,并持有对所有同事对象的引用,以便在收到消息时将其转发给正确的同事对象。
简单来说,就是Colleague
需要持有Mediator
对象,并直接与Mediator
对象通信,Mediator
对象通过通信内容进行相关处理。其中Mediator
对象也需要持有ConcreteColleague[X]
对象;