一:背景
当在一个系统中,存在大量的对象的时候,对象之间的相互调用连接会大大增加系统的复杂性,对系统行为的改动也会变得十分困难;根据‘迪米特法则’,如果两个类不必彼此直接通信,那么这两个类就不应该发生直接的相互作用。这里,我们就可以引入一个中介者,将系统的网状结构变成以中介者为中心的星形结构。
二:概述
1、定义
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互。
2、类图结构
三:实例分析
下面拿大话设计模式中联合国的例子来说
对应于类图,联合国就相当于一个中介者,用以传递国家之间的消息。
代码:
联合国
public abstract class UnitedNations {
public abstract void declare(String message, Country colleague);
}
国家
public abstract class Country {
protected UnitedNations mediator;
public Country(UnitedNations mediator){
this.mediator = mediator;
}
public void declare(String message){
mediator.declare(message, this);
}
public void getMessage(String message){
System.out.println(message);
}
}
联合国的实现类:联合国安理会
public class UnitedNationsSecurityCouncil extends UnitedNations {
//定义了两个国家之间的交互
private Country colleague1;
private Country colleague2;
public void setColleague1(Country usa){
colleague1 = usa;
}
public void setColleague2(Country iraq){
colleague2 = iraq;
}
@Override
public void declare(String message, Country colleague) {
if (colleague == colleague1){
colleague2.getMessage(message);
}else{
colleague1.getMessage(message);
}
}
}
具体国家:
美国
public class USA extends Country {
public USA(UnitedNations mediator) {
super(mediator);
}
//声明
public void declare(String message){
mediator.declare(message, this);
}
//获得消息
public void getMessage(String message){
System.out.println("USA获取消息:"+message);
}
}
伊拉克
public class Iraq extends Country {
public Iraq(UnitedNations mediator) {
super(mediator);
}
//声明
public void declare(String message){
mediator.declare(message,this);
}
//获取消息
public void getMessage(String message){
System.out.println("Iraq获取消息:"+message);
}
}
来看看客户端是如何操作的:
UnitedNationsSecurityCouncil unsc = new UnitedNationsSecurityCouncil();
Country usa = new USA(unsc);
Country iraq = new Iraq(unsc);
unsc.setColleague1(usa);
unsc.setColleague2(iraq);
usa.declare("不要挑衅我!");
iraq.declare("喜欢挑衅你。");
中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合,如.NET中的Form窗体就是一个中介者;但是由于ConcreteMediator控制了集中化,于是把交互复杂性变成了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。
参考书籍:《大话设计模式》