10.25
中介者模式
下面是一个简单的示例,展示了如何在 Java 中实现中介者模式:
// 中介者接口
interface Mediator {
void sendMessage(String message, Colleague colleague);
}
// 抽象同事类
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void receiveMessage(String message);
public abstract void sendMessage(String message);
}
// 具体同事类A
class ConcreteColleagueA extends Colleague {
public ConcreteColleagueA(Mediator mediator) {
super(mediator);
}
public void receiveMessage(String message) {
System.out.println("Colleague A received message: " + message);
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
}
// 具体同事类B
class ConcreteColleagueB extends Colleague {
public ConcreteColleagueB(Mediator mediator) {
super(mediator);
}
public void receiveMessage(String message) {
System.out.println("Colleague B received message: " + message);
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
}
// 具体中介者类
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;
}
public void sendMessage(String message, Colleague colleague) {
if (colleague == colleagueA) {
colleagueB.receiveMessage(message);
} else if (colleague == colleagueB) {
colleagueA.receiveMessage(message);
}
}
}
// 客户端代码
public class MediatorPatternExample {
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 from Colleague A!");
colleagueB.sendMessage("Hi from Colleague B!");
}
}