中介模式就是把软件实体的网状结构都抽离成了只和 一个中介实体连接的星形结构;
代码实现:
中介接口
package mediator;
/***
* 中介接口
* */
public interface Mediator {
// 注册
void register(String dname, Department d);
// 发出命令
void command(String name);
}
中介实现类
package mediator;
import java.util.HashMap;
import java.util.Map;
/**
* 老总类
* */
public class M1 implements Mediator{
private Map<String, Department> map = new HashMap<String, Department>();
@Override
public void register(String dname, Department d) {
// TODO Auto-generated method stub
map.put(dname, d);
}
@Override
public void command(String name) {
// TODO Auto-generated method stub
map.get(name).selfAction();
}
}
同事接口
package mediator;
/**
*
* 同事接口
* */
public interface Department {
// 做本部门的事情
void selfAction();
// 向总经理发出申请
void outAction();
}
同事实现类
package mediator;
/**
* 同事1 研发部
*
* */
public class D1 implements Department {
private Mediator m;
public D1(Mediator m) {
super();
this.m = m;
m.register("D1", this);
}
@Override
public void selfAction() {
// TODO Auto-generated method stub
System.out.println("专心研发产品");
}
@Override
public void outAction() {
// TODO Auto-generated method stub
System.out.println("研发资金不够了,需要申请");
m.command("D3");
}
}
package mediator;
/**
* 同事2 市场部
*
* */
public class D2 implements Department{
private Mediator m;
public D2(Mediator m) {
super();
this.m = m;
m.register("D2", this);
}
@Override
public void selfAction() {
// TODO Auto-generated method stub
System.out.println("专心做市场");
}
@Override
public void outAction() {
// TODO Auto-generated method stub
System.out.println("市场资金不够了,需要申请");
m.command("D3");
}
}
package mediator;
/**
* 同事3 财务部
*
* */
public class D3 implements Department{
private Mediator m;
public D3(Mediator m) {
super();
this.m = m;
m.register("D3", this);
}
@Override
public void selfAction() {
// TODO Auto-generated method stub
System.out.println("数钱,发钱");
}
@Override
public void outAction() {
// TODO Auto-generated method stub
System.out.println("没钱了,需要市场去开拓");
m.command("D1");
}
}
客户端调用
package mediator;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mediator m= new M1();
Department d1 = new D1(m);
Department d2 = new D2(m);
Department d3 = new D3(m);
// 专心研发产品
// 研发资金不够了,需要申请
// 数钱,发钱
d1.selfAction();
d1.outAction();
}
}