中介者模式是一种行为型设计模式,它定义了一个中介对象来封装一系列对象之间的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
// 中介者接口
public interface Mediator {
void notify(Component sender, String event);
}
// 抽象组件
public abstract class Component {
protected Mediator mediator;
public Component(Mediator mediator) {
this.mediator = mediator;
}
public abstract void send(String event);
public abstract void receive(String event);
}
// 具体组件A
public class ConcreteComponentA extends Component {
public ConcreteComponentA(Mediator mediator) {
super(mediator);
}
@Override
public void send(String event) {
mediator.notify(this, event);
}
@Override
public void receive(String event) {
System.out.println("Component A received: " + event);
}
}
// 具体中介者
public class ConcreteMediator implements Mediator {
private ConcreteComponentA componentA;
private ConcreteComponentB componentB;
public void setComponentA(ConcreteComponentA componentA) {
this.componentA = componentA;
}
public void setComponentB(ConcreteComponentB componentB) {
this.componentB = componentB;
}
@Override
public void notify(Component sender, String event) {
if (sender == componentA) {
componentB.receive(event);
} else {
componentA.receive(event);
}
}
}