场景:mvc模式(其中的c,控制器就是一个中介者对象,m,v都和他打交道);java.lang.reflect.Method#invoke()
例子:比如一个公司有市场部,开发部,财务部,之间的沟通就是通过总经理(中介者)来相互调用
Mediator.java(中介者接口)
public interface Mediator {
void register(String dname,Department d);
void command(String dname);
}
President.java(实现中介者接口的具体类)
public class President implements Mediator {
private Map<String,Department> map = new HashMap<String , Department>();
@Override
public void command(String dname) {
map.get(dname).selfAction();
}
@Override
public void register(String dname, Department d) {
map.put(dname, d);
}
}
Deparment.java(同事类接口)
//同事类的接口
public interface Department {
void selfAction(); //做本部门的事情
void outAction(); //向总经理发出申请
}
Finacial.java(财务部)
public class Finacial implements Department {
private Mediator m; //持有中介者(总经理)的引用
public Finacial(Mediator m) {
super();
this.m = m;
m.register("finacial", this);
}
@Override
public void outAction() {
System.out.println("汇报工作!没钱了,钱太多了!怎么花?");
}
@Override
public void selfAction() {
System.out.println("数钱!");
}
}
Market.java(市场部)
public class Market implements Department {
private Mediator m; //持有中介者(总经理)的引用
public Market(Mediator m) {
super();
this.m = m;
m.register("market", this);
}
@Override
public void outAction() {
System.out.println("汇报工作!项目承接的进度,需要资金支持!");
m.command("finacial");
}
@Override
public void selfAction() {
System.out.println("跑去接项目!");
}
}
Deparment.java(开发部)
public class Development implements Department {
private Mediator m; //持有中介者(总经理)的引用
public Development(Mediator m) {
super();
this.m = m;
m.register("development", this);
}
@Override
public void outAction() {
System.out.println("汇报工作!没钱了,需要资金支持!");
}
@Override
public void selfAction() {
System.out.println("专心科研,开发项目!");
}
}
测试
public class Client {
public static void main(String[] args) {
Mediator m = new President();
Market market = new Market(m);
Development devp = new Development(m);
Finacial f = new Finacial(m);
market.selfAction();
market.outAction();
}
}