定义
中介者模式是一种行为设计模式,它减少了类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理所有的通信,并支持易维护的方式来协调多个类。
示例代码
以下是一个简单的Java代码示例,演示了中介者模式的使用:
首先,我们定义一个中介者接口:
java
public interface Mediator {
void sendMessage(String message, Colleague colleague);
}
然后,我们创建实现中介者接口的具体中介者类:
java
import java.util.ArrayList;
import java.util.List;
public class ConcreteMediator implements Mediator {
private List<Colleague> colleagues;
public ConcreteMediator() {
this.colleagues = new ArrayList<>();
}
public void addColleague(Colleague colleague) {
this.colleagues.add(colleague);
}
@Override
public void sendMessage(String message, Colleague originator) {
for (Colleague colleague : colleagues) {
//don't tell ourselves
if (colleague != originator) {
colleague.receive(message);
}
}
}
}
接着,我们定义一个同事类:
java
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator m) {
mediator = m;
}
//send a message via the mediator
public void send(String message) {
mediator.sendMessage(message, this);
}
//get access to the mediator
public Mediator getMediator() {return mediator;}
public abstract void receive(String message);
}
然后,我们创建实现同事抽象类的具体同事类:
java
public class ConcreteColleague extends Colleague {
public ConcreteColleague(Mediator m) {
super(m);
}
public void receive(String message) {
System.out.println("Colleague Received: " + message);
}
}
最后,我们可以在客户端代码中使用这些类:
java
public class MediatorPatternDemo {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleague colleague1 = new ConcreteColleague(mediator);
ConcreteColleague colleague2 = new ConcreteColleague(mediator);
mediator.addColleague(colleague1);
mediator.addColleague(colleague2);
colleague1.send("Hello, from colleague1!");
colleague2.send("Hello, from colleague2!");
}
}
在这个例子中,MediatorPatternDemo
类使用ConcreteMediator
类和ConcreteColleague
类来创建一个中介者模式的示例。