中介者模式(Mediator),是一种行为性模型,行为型模式关注的是系统中对象之间的相互交互,解决系统在运行时对象之间的相互通信和协作,进一步明确对象的职责。相比来说,创建型模式关注对象的创建过程,结构型模式关注对象和类的组合关系。
模式的职责
如果一个系统中对象之间的关系呈现网状结构,对象之间存在大量的多对多关系,将导致关系及其复杂,这些对象成为“同时对象”。我们可以引入一个中介者对象,使各个同事对象只跟中介者对象打交道,将复杂的网络结构化解为星形结构。
模式的实现
//中介者,负责做中介类
public interface Medium {
//其他类让中介者帮助中介的注册方法
void register(String name,Department d);
//对其他类的控制方法
void command(String name);
}
class President implements Medium{
private Map <String,Department>map = new HashMap<String,Department>();
public void command(String name) {
//中介者调用相关类的相关方法
map.get(name).selfAction();
}
public void register(String name, Department d) {
//被管理类注册到中介者中来
map.put(name, d);
}
}
//被中介者管理的类的抽象
public interface Department {
//自己做的
void selfAction();
//向中介者申请的方法
void outAction();
}
class Development implements Department{
private Medium m;//持有中介者的引用
public Development(Medium m){
super();
this.m = m;
m.register("development", this);
}
public void outAction() {
//对外的报告或者需求
System.out.println("这是研发的进度。研发快没钱了,快给点资金支持!");
//可以通过中介者的相关方法调用需要的方法
m.command("final");
}
public void selfAction() {
//自己的方法的实现
System.out.println("研发部在拼命的研发中");
}
}
class Final implements Department{
private Medium m;//持有中介者的引用
public Final(Medium m){
super();
this.m = m;
m.register("development", this);
}
public void outAction() {
//对外的报告或者需求
System.out.println("这是财务部。已经把相应资金给出");
}
public void selfAction() {
//自己的方法的实现
System.out.println("财务部在给相应部门提供资金");
}
}
class Market implements Department{
private Medium m;//持有中介者的引用
public Market(Medium m){
super();
this.m = m;
m.register("development", this);
}
public void outAction() {
//对外的报告或者需求
System.out.println("这是市场部。这是我跑的需求和业务");
}
public void selfAction() {
//自己的方法的实现
System.out.println("市场部在外跑需求");
}
}
//客户端调用
public class Client {
public static void main(String[] args) {
//先创建中介者对象
Medium m = new President();
//然后创建被中介者管理的对象
Market market = new Market(m);
Development d = new Development(m);
Final f = new Final(m);
//再调用需要调用的方法
market.selfAction();
f.selfAction();
d.selfAction();
}
}
模式的本质
解耦多个被处理对象之间的交互关系,每个对象都持有中介者对象的引用,只跟中介者对象打交道。我们通过中介者对象同意管理这些交互关系。
模式的一些应用
MVC模式中的C控制器,就是一个中介者对象M和V都和它打交道。
窗口游戏程序,窗口软件开发中窗口对象也是一个中介者对象。
图形界面花开发GUI中,多个组件之间的交互,可以通过一个中介者对象来解决,可以是整体的窗口对象或者是DOM对象。
Java.lang.reflect.Method#invoke()