用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地互相引用,从而使其耦合松散,而且可以独立地改变它们之间的交互
如没有联合国之前,国与国沟通需要建立联系,当国家增多时,形成网状结构错综复杂,当引入联合国这个中介时,它们就不必直接通信,变为星状结构
Country类,内部维护UnitedNations,每个子类都有发送和接收信息
public class Country {
protected UnitedNations mUnitedNations;
public Country(UnitedNations unitedNations) {
mUnitedNations = unitedNations;
}
}
class USA extends Country {
public USA(UnitedNations unitedNations) {
super(unitedNations);
}
public void declare(String msg) {
mUnitedNations.declare(msg, this);
}
public void getMessage(String message) {
System.out.println("USA获取信息: " + message);
}
}
class China extends Country {
public China(UnitedNations unitedNations) {
super(unitedNations);
}
public void declare(String msg) {
mUnitedNations.declare(msg, this);
}
public void getMessage(String message) {
System.out.println("China获取信息: " + message);
}
}
UnitedNations作为中介者,具体子类处理信息的传递
abstract class UnitedNations {
abstract void declare(String msg, Country country);
}
class UnitedNationsSecurityCouncil extends UnitedNations {
private USA mUSA;
private China mChina;
public void setUSA(USA USA) {
mUSA = USA;
}
public void setChina(China china) {
mChina = china;
}
@Override
void declare(String msg, Country country) {
if (country == mUSA) {
mChina.getMessage(msg);
} else if (country == mChina) {
mUSA.getMessage(msg);
}
}
}
当使用时
UnitedNationsSecurityCouncil securityCouncil = new UnitedNationsSecurityCouncil();
USA usa = new USA(securityCouncil);
China china = new China(securityCouncil);
securityCouncil.setChina(china);
securityCouncil.setUSA(usa);
usa.declare("hello");
china.declare("你好");
把交互复杂性变为中介者的复杂性,当出现多对多交互时,需先考虑设计是否合理再采用中介者模式