中介模式(Mediator Pattern)是一种行为设计模式,它定义了一个中介对象来封装一系列的对象交互,从而使各个对象不需要显式地相互引用,从而降低对象之间的耦合度,提高系统的可扩展性和可维护性
工作原理:
代码实现:
/**
* 抽象同事类
*/
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
/**
* 抽象中介者
*/
public interface Mediator {
/**
* 发送消息方法,得到同事对象和发送消息
*/
void send(String messag,Colleague colleague);
}
/**
* 具体实现同事类1
*/
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void send(String message){
this.mediator.send(message,this);
}
public void notify(String message){
System.out.println("同事1得到消息: " + message);
}
}
/**
* 具体实现同事类2
*/
public class ConcreteColleague2 extends Colleague{
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void send(String message){
this.mediator.send(message,this);
}
public void notify(String message){
System.out.println("同事2得到消息: " + message);
}
}
/**
* 具体中介者
*/
public class ConcreteMediator implements Mediator{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public ConcreteMediator(){}
public void setConcreteMediator(ConcreteColleague1 colleague1) {
this.colleague1 = colleague1;
}
public void setConcreteMediator(ConcreteColleague2 colleague2) {
this.colleague2 = colleague2;
}
/**
* 相互传递消息
*/
@Override
public void send(String message, Colleague colleague){
if (colleague == colleague1){
colleague2.notify(message);
}else{
colleague1.notify(message);
}
}
}
/**
* 中介模式客户端
*/
public class MediatorDemo {
public static void main(String[] args) {
// 创建具体中介
ConcreteMediator concreteMediator = new ConcreteMediator();
// 创建同事1,2
ConcreteColleague1 concreteColleague1 = new ConcreteColleague1(concreteMediator);
ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(concreteMediator);
concreteMediator.setConcreteMediator(concreteColleague1);
concreteMediator.setConcreteMediator(concreteColleague2);
concreteColleague1.send("你吃了么?");
concreteColleague2.send("没呢");
}
}
打印输出:
Connected to the target VM, address: '127.0.0.1:12313', transport: 'socket'
同事2得到消息: 你吃了么?
同事1得到消息: 没呢
Disconnected from the target VM, address: '127.0.0.1:12313', transport: 'socket'