中介者模式是一种行为型设计模式,它包含了一个中介对象,该对象通常用于简化一组对象与对象之间的通信。中介者使得各个同事对象不需要显式地相互引用,从而使其在处理一组对象之间的交互时更加灵活和易于维护。
以下是一个简单的Java中介者模式的实现示例:
// 同事类的基本接口
interface Colleague {
void sendMessage(String message);
}
// 具体的同事类
class ConcreteColleagueA implements Colleague {
private Mediator mediator;
public ConcreteColleagueA(Mediator mediator) {
this.mediator = mediator;
mediator.register(this);
}
@Override
public void sendMessage(String message) {
System.out.println("同事A发送信息:" + message);
}
}
class ConcreteColleagueB implements Colleague {
private Mediator mediator;
public ConcreteColleagueB(Mediator mediator) {
this.mediator = mediator;
mediator.register(this);
}
@Override
public void sendMessage(String message) {
System.out.println("同事B发送信息:" + message);
}
}
// 中介者接口
interface Mediator {
void register(Colleague colleague);
void send(String message, Colleague colleague);
}
// 中介者类
class ConcreteMediator implements Mediator {
private ConcreteColleagueA colleagueA;
private ConcreteColleagueB colleagueB;
@Override
public void register(Colleague colleague) {
if (colleague instanceof ConcreteColleagueA) {
colleagueA = (ConcreteColleagueA) colleague;
} else if (colleague instanceof ConcreteColleagueB) {
colleagueB = (ConcreteColleagueB) colleague;
}
}
@Override
public void send(String message, Colleague colleague) {
if (colleague == colleagueA) {
colleagueB.sendMessage(message);
} else {
colleagueA.sendMessage(message);
}
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
Colleague colleagueA = new ConcreteColleagueA(mediator);
Colleague colleagueB = new ConcreteColleagueB(mediator);
colleagueA.sendMessage("你好,同事B");
colleagueB.sendMessage("你好,同事A");
}
}
在这个示例中,我们定义了一个Mediator接口和一个ConcreteMediator中介者类。同时,我们定义了两个同事类ConcreteColleagueA和ConcreteColleagueB,它们都实现了Colleague接口。在main方法中,我们创建了一个中介者对象和两个同事对象,并展示了它们如何通过中介者进行通信。这个简单的例子展示了中介者模式的基本原理和结构。