调停者本质是门面模式另一个面,门面模式相当于从外面看,调停者相当于从内部看,都是把原来复杂的类联系转为星形。
image.png image.png第一步,新建一个抽象类作为星形的核心类,跟周边类打交道,同时被打交道的周边类也抽象一个
public abstract class Mediator {
//协调动作,谁通知中介者,中介者在通知第三方干活
abstract void coordinate(String userName, String msg, Colleague colleague) ;
}
public abstract class Colleague {
protected String name;
protected Mediator mediator;
public Colleague(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
public void getMsg (String userName, String msg){
System.out.println("【"+this.name+"】收到"+"【"+userName+"】协调任务:["+msg+"]");
}
public void sendMsg (String name,String msg,Colleague colleague){
System.out.println("【"+name+"】发起协调任务:"+ msg);
mediator.coordinate(name,msg,colleague);
}
}
上面两个抽象类你中有我,我中有你,Mediator 严格来讲必须在Colleague 中出现,所以用构造注入,而Colleague 在Mediator 中是多个存在,可以不是全部拥有,可以用set注入。
第二步添加几个抽象类的实现
public class AColleagueImpl extends Colleague{
public AColleagueImpl(String name, Mediator mediator) {
super(name, mediator);
}
}
public class BColleagueImpl extends Colleague{
public BColleagueImpl(String name, Mediator mediator) {
super(name, mediator);
}
}
public class CColleagueImpl extends Colleague{
public CColleagueImpl(String name, Mediator mediator) {
super(name, mediator);
}
}
public class MediatorImpl extends Mediator{
@Override
void coordinate(String userName, String msg, Colleague colleague) {
System.out.println("中介者接收【"+userName+"】的协调任务:" + msg);
System.out.println("经理转发【"+userName+"】协调任务,@【"+colleague.name+"】");
colleague.getMsg(userName,msg);
}
}
调停者本质就是封装然后转发请求
public class Client {
public static void main(String[] args) {
Mediator mediator = new MediatorImpl() ;
Colleague employeeA = new AColleagueImpl("张三",mediator) ;
Colleague employeeB = new BColleagueImpl("李四",mediator) ;
employeeA.sendMsg(employeeA.name,"需要产品文档",employeeB);
}
}
\\console
\*【张三】发起协调任务:需要产品文档
中介者接收【张三】的协调任务:需要产品文档
经理转发【张三】协调任务,@【李四】
【李四】收到【张三】协调任务:[需要产品文档]*\
网友评论