概念:也称为调停者模式。用一个中介者对象封装一系列对象的交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
- 抽象中介者:定义中介者的操作。
- 具体中介者:实现抽象中介者定义的操作,并持有被调停者对象。
- 抽象被调停者:定义被调停者的操作。
- 具体被调停者:实现具体操作,通过中介者进行交互。
以下用一个同事之间沟通的例子来帮助大家理解。
public interface Mediator {void changed(Colleague colleague);void register(Colleague colleague);
}public interface Colleague {void send(String message);void receive(String message);
}public class ConcreteMediator implements Mediator {private List<Colleague> colleagues = new ArrayList<>();public void register(Colleague colleague) {colleagues.add(colleague);}@Overridepublic void changed(Colleague colleague) {// 假设每个同事收到消息后都向所有其他同事发送消息for (Colleague c : colleagues) {if (!c.equals(colleague)) {c.receive("Message from " + colleague.getClass().getSimpleName());}}}
}public class ConcreteColleagueA implements Colleague {private Mediator mediator;public ConcreteColleagueA(Mediator mediator) {this.mediator = mediator;mediator.register(this);}@Overridepublic void send(String message) {System.out.println("Colleague A sends: " + message);mediator.changed(this);}@Overridepublic void receive(String message) {System.out.println("Colleague A receives: " + message);}
}public class ConcreteColleagueB implements Colleague {private Mediator mediator;public ConcreteColleagueB(Mediator mediator) {this.mediator = mediator;mediator.register(this);}@Overridepublic void send(String message) {System.out.println("Colleague B sends: " + message);mediator.changed(this);}@Overridepublic void receive(String message) {System.out.println("Colleague B receives: " + message);}
}public class Demo {public static void main(String[] args) {ConcreteMediator mediator = new ConcreteMediator();Colleague colleagueA = new ConcreteColleagueA(mediator);Colleague colleagueB = new ConcreteColleagueB(mediator);colleagueA.send("Hello from A");colleagueB.send("Hello from B");}
}
如果大家需要视频版本的讲解,欢迎关注我的B站:
【天哥不爱学习的个人空间-哔哩哔哩】 https://b23.tv/HxwqjXl