中介者模式
下面是一個簡單的示例,展示瞭如何在 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!");
}
}