- 场景
假如没有总经理,下面三个部门:财务部,市场部,研发部。财务部要发工资,让大家核对公司需要跟市场部和研发部都通气;市场部要接新项目,需要研发部处理技术、需要财务部出资金。市场部跟各个部门打交道。虽然只有三个部门,但是关系非常乱。
实际上,公司都有总经理。各个部门有什么事情都通报到总经理这里,总经理再通知各个相关部门。这就是一个典型的“中介者模式”,总经理起到一个中介、协调的作用。
- 核心
如果一个系统中对象之间的联系呈现为网状结构,对象之间存在大量多对多关系,将导致关系及其复杂。我们可以引入一个中介者对象,使各个对象只跟中介者打交道,将复杂的网络结构化解为星型结构。
- 中介者模式的本质
解耦多个对象之间的交互关系。每个对象都持有中介者对象的引用,只跟中介者对象打交道。我们通过中介者对象统一管理这些交互关系。
- 中介者模式实现
/**
*部门接口
*/
public interface Department {
void selfAction();//做本部门事情
void outAction();//向总经理发出申请
}
//研发部
public class Development implements Department {
private Mediator m;//持有中介者对象引用
public Development(Mediator m) {
super();
this.m = m;
m.register("development", this);
}
public void outAction() {
System.out.println("汇报工作!没钱了,需要资金支持!");
m.command("finacial");//告诉总经理需要资金,让总经理去协调
}
public void selfAction() {
System.out.println("开发项目");
}
}
//财务部
public class Finacial implements Department {
private Mediator m;//持有中介者对象引用
public Finacial(Mediator m) {
super();
this.m = m;
m.register("finacial", this);
}
public void outAction() {
System.out.println("汇报工作!怎么分配资金!");
m.command("market");//告诉总经理需要市场销售单据,让总经理去协调
}
public void selfAction() {
System.out.println("预算资金,结算资金");
}
}
//财务部
public class Market implements Department {
private Mediator m;//持有中介者对象引用
public Market(Mediator m) {
super();
this.m = m;
m.register("market", this);
}
public void outAction() {
System.out.println("汇报工作!需要资金和技术支持!");
m.command("finacial");//告诉总经理需要资金,让总经理去协调
m.command("development");//告诉总经理需要技术支持,让总经理去协调
}
public void selfAction() {
System.out.println("见客户,谈项目");
}
}
/**
* 中介者接口
*/
public interface Mediator {
void register(String dname,Department d);
void command(String dname);//向部门发出命令
}
//总经理类(中介者的实现类)
public class President implements Mediator{
private Map<String,Department>map = new HashMap<String,Department>();
public void command(String dname) {
map.get(dname).selfAction();//将需求向其他相关部门转达进行协调
}
public void register(String dname, Department d) {
map.put(dname, d);
}
}
public class Client {
public static void main(String[] args) {
Mediator m = new President();//总经理(中介者)
Development dev = new Development(m);
Finacial finacial = new Finacial(m);
Market market = new Market(m);
market.selfAction();
market.outAction();//需要其他部门协调
}
}
- 中介者模式类图: