23种设计模式之中介者模式
程序员文章站
2024-03-23 08:40:04
...
中介者模式本质
- 解耦多个部门对象之间的交互关系。每个对象都持有中介者对象的引用,只跟中介者对象打交道。我们通过中介者对象统一管理这些交互关系
android最常见的场景
- MVC模式(其中的C),控制器就是一个中介者对象。M和V都和它打交道
总经理接口:总经理有两件事情:注册每个部门,向部门发送命令
//总经理接口
public interface Mediator {
void register(String dname,Department d);
void command(String dname);
}
部门接口:每个部门也只干两件事情,做自己本职工作和向总经理发送请求
public interface Department {
void selfAction();//本职工作
void outAction();//向总经理发送请求
}
科研部门
public class Development implements Department {
Mediator mediator;
public Development(Mediator mediator) {
this.mediator = mediator;
mediator.register("development",this);
}
@Override
public void selfAction() {
System.out.println("专心科研,开发好资源!");
}
@Override
public void outAction() {
System.out.println("汇报工作!没钱了,需要资金支持!");
mediator.command("finacial");
}
}
市场部部门
public class Market implements Department {
Mediator mediator;//总经理,中间者
public Market(Mediator mediator) {
this.mediator = mediator;
mediator.register("market",this);//注册当前
}
@Override
public void selfAction() {
System.out.println("市场部跑业务,拉妹子去了");
}
@Override
public void outAction() {
System.out.println("报告老板!市场部没钱了,请求发工资");
mediator.command("finacial");//向财务部发命令
}
}
财务部部门
public class Finacial implements Department {
Mediator mediator;
public Finacial(Mediator mediator) {
this.mediator = mediator;
mediator.register("finacial", this);
}
@Override
public void selfAction() {
System.out.println("我是财务部,马上发钱!");
}
@Override
public void outAction() {
System.out.println("汇报工作!没钱了,赶紧找人跑业务啊");
mediator.command("market");
}
}
总经理实现
public class President implements Mediator {
private Map<String,Department> map=new HashMap<>();
@Override
public void register(String dname, Department d) {
map.put(dname,d);
}
@Override
public void command(String dname) {
map.get(dname).selfAction();
}
}
测试
Mediator mediator = new President();//总经理
Market market = new Market(mediator);//市场部
Development development = new Development(mediator);//科研部
Finacial finacial = new Finacial(mediator);//财务部
development.selfAction();//
development.outAction();
finacial.outAction();
market.outAction();