概念:就是相当于一个注册中心,或者是一个消息中间件,如聊天室中各个用户聊天的消息都可以通过该注册中心将消息发到聊天室。
用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
整体结构就是 各个同事类之间复杂的关系都交给中介对象去解决,实现了对象之间的解耦,尽可能的遵守迪米特法则。
什么叫同事类关系 ?
指的是 当一个类发生改变时候会影响另一个类的操作,那么这俩个类就是同事类。
package mediator;
import java.util.HashMap;
import java.util.Map;
/**
* @Classname Mediator
* @Description TODO
* @Date 2021/3/25 22:40
* @Created by 86386
*/
public abstract class Mediator {
public abstract void register(String departmentName, Department department);
public abstract void command(String departmentName);
}
class ConcrateMediator extends Mediator{
private Map<String, Department> map = new HashMap<>();
@Override
public void register(String departmentName, Department department) {
map.put(departmentName, department);
}
@Override
public void command(String departmentName) {
map.get(departmentName).selfAction();
}
}
interface Department {
void selfAction();
void outAction();
}
class Research implements Department {
private Mediator mediator; //持有中介者的引用,本案例对应的中介者就是总经理
public Research(Mediator mediator) {
this.mediator = mediator;
mediator.register("Research", this);
}
@Override
public void selfAction() {
System.out.println("研发部:专心研发");
}
@Override
public void outAction() {
System.out.println("研发部:汇报研发进度,请求资金支持!");
mediator.command("Finance");
}
}
class Marketing implements Department {
private Mediator mediator; //持有中介者的引用,本案例对应的中介者就是总经理
public Marketing(Mediator mediator) {
this.mediator = mediator;
mediator.register("Marketing", (Department) this);
}
@Override
public void selfAction() {
System.out.println("市场部:拉项目");
}
@Override
public void outAction() {
System.out.println("市场部:汇报拉项目进度,请求资金支持!");
mediator.command("Finance");
}
}
class Finance implements Department {
private Mediator mediator; //持有中介者的引用,本案例对应的中介者就是总经理
public Finance(Mediator mediator) {
this.mediator = mediator;
mediator.register("Finance", this);
}
@Override
public void selfAction() {
System.out.println("财务部:管理资金,资金流动");
}
@Override
public void outAction() {
System.out.println("财务部:汇报工作,钱款充足,如何规划!");
}
}
class Client {
public static void main(String[] args) {
Mediator mediator = new ConcrateMediator();
Research research = new Research(mediator);
Finance finance = new Finance(mediator);
Marketing marketing = new Marketing(mediator);
// research相关内外方法
System.out.println("-research selfAction-");
research.selfAction();
System.out.println("-research outAction-");
research.outAction();
System.out.println();
// marketing相关内外方法
System.out.println("-marketing selfAction-");
marketing.selfAction();
System.out.println("-marketing outAction-");
marketing.outAction();
System.out.println();
// finance相关内外方法
System.out.println("-finance selfAction-");
finance.selfAction();
System.out.println("-finance outAction-");
finance.outAction();
}
}