书上的原句:
中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
一个例子:如果中国和美国之间的交涉通过联合国机构间接转发,而不是面对面的交涉,那么代码可以写成这样:
public class Main {
public static void main(String[] args) {
UnitedNationsSecurityCouncil unitedNations = new UnitedNationsSecurityCouncil();
Country china = new China(unitedNations);
Country usa = new USA(unitedNations);
unitedNations.setChina(china);
unitedNations.setUsa(usa);
china.send("给个美国特产我");
usa.send("就不给");
}
}
//联合国机构(充当中介者)
abstract class UnitedNations {
//接收消息,并转发给另一个国家
abstract void declare(String message, Country country);
}
//国家(充当同事类)
abstract class Country {
protected UnitedNations mediator;
public Country(UnitedNations mediator) {
this.mediator = mediator;
}
//发送消息
abstract void send(String message);
//接收消息
abstract void get(String message);
}
//联合国安全理事会(具体的中介者)
class UnitedNationsSecurityCouncil extends UnitedNations{
private Country china;
private Country usa;
public void setChina(Country china) {
this.china = china;
}
public void setUsa(Country usa) {
this.usa = usa;
}
@Override
void declare(String message, Country country) {
if (china == country){
usa.get(message);
}
else if (usa == country){
china.get(message);
}
}
}
//中国
class China extends Country{
public China(UnitedNations mediator) {
super(mediator);
}
@Override
void send(String message) {
mediator.declare(message, this);
}
@Override
void get(String message) {
System.out.println("中国收到消息:"+message);
}
}
//美国
class USA extends Country{
public USA(UnitedNations mediator) {
super(mediator);
}
@Override
void send(String message) {
mediator.declare(message, this);
}
@Override
void get(String message) {
System.out.println("美国收到消息:"+message);
}
}
运行结果:
美国收到消息:给个美国特产我
中国收到消息:就不给
中介者的出现减少了各个同事类(上述国家)之间的耦合,使得可以独立地改变和复用各个同事类和中介者,而且,把对象如何进行协作进行了抽象,将中介者作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
但是,正由于中介者的控制集中化了,因此大大增加了中介者的复杂性,如果中介者里出错了,可能会导致整个系统不能正常运作