中介者模式:
用一个中介对象来封装一系列的对象交互,中介者使个对象不需要显示地相互引用,从而使其耦合松散,可以独立地改变它们之间的交互。
// 国家类
public abstract class Country {
private UnionNations un;
public Country(UnionNations un) {
this.un = un;
}
public UnionNations getUn() {
return un;
}
public void setUn(UnionNations un) {
this.un = un;
}
public abstract void declare(String message);
public abstract void getMessage(String message);
}
// 伊拉克
public class Iraq extends Country {
public Iraq(UnionNations un) {
super(un);
}
@Override
public void declare(String message) {
this.getUn().declare(message, this);
}
@Override
public void getMessage(String message) {
System.out.println("Iraq has get the message: " + message);
}
}
// 美国
public class USA extends Country {
public USA(UnionNations un) {
super(un);
}
@Override
public void declare(String message) {
this.getUn().declare(message, this);
}
@Override
public void getMessage(String message) {
System.out.println("USA has get the message: " + message);
}
}
// 联合国机构类
public abstract class UnionNations {
public abstract void declare(String message, Country country);
}
// 联合国安全理事会
public class UnionNationsSecurityCouncil extends UnionNations {
private USA usa;
private Iraq iraq;
public USA getUsa() {
return usa;
}
public void setUsa(USA usa) {
this.usa = usa;
}
public Iraq getIraq() {
return iraq;
}
public void setIraq(Iraq iraq) {
this.iraq = iraq;
}
@Override
public void declare(String message, Country country) {
if (country instanceof USA) {
iraq.getMessage(message);
} else {
usa.getMessage(message);
}
}
}
public class MediatorMain {
public static void main(String[] args) {
UnionNationsSecurityCouncil unsc = new UnionNationsSecurityCouncil();
// 具体对象记住中介者
USA usa = new USA(unsc);
Iraq iraq = new Iraq(unsc);
// 中介者记住具体对象
unsc.setIraq(iraq);
unsc.setUsa(usa);
// 中介者负责转发消息
usa.declare("stop the unclear weapon's development!");
iraq.declare("I have no nuclear wapons!");
}
}
应用场景:
中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合。