中介者模式(Mediator):用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
package mediator;
/**
* 中介者模式(Mediator)
* 联合国机构
*/
public abstract class UnitedNations {
// 声明
public abstract void declare(String message, Country colleague);
}
package mediator;
/**
* 中介者模式(Mediator)
* 国家
*/
public abstract class Country {
protected UnitedNations mediator;
public Country(UnitedNations mediator) {
this.mediator = mediator;
}
}
package mediator;
/**
* 中介者模式(Mediator)
* 美国
*/
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("美国获得对方信息:" + message);
}
}
package mediator;
/**
* 中介者模式(Mediator)
* 伊拉克
*/
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("伊拉克获得对方信息:" + message);
}
}
package mediator;
/**
* 中介者模式(Mediator)
* 联合国安理会
*/
public class UnitedNationsSecurityCouncil extends UnitedNations {
private USA colleague1;
private Iraq colleague2;
public void setColleague1(USA colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(Iraq colleague2) {
this.colleague2 = colleague2;
}
@Override
public void declare(String message, Country colleague) {
if (colleague == colleague1) {
colleague2.getMessage(message);
} else {
colleague1.getMessage(message);
}
}
}
package mediator;
/**
* 中介者模式(Mediator)
* 客户端main方法
*/
public class Client {
public static void main(String[] args) {
UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil();
USA c1 = new USA(UNSC);
Iraq c2 = new Iraq(UNSC);
UNSC.setColleague1(c1);
UNSC.setColleague2(c2);
c1.declare("不准研制核武器,否则要发动战争!");
c2.declare("我们没有核武器,也不怕侵略!");
}
}