中介者模式(Mediator),用一个中介对象来封装一系列的对象的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
主方法
public class main {
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("我们没有核武器,也不怕侵略");
c1.declare("发动战争!");
}
}
中介者抽象类
public abstract class UnitedNations {
public abstract void declare(String message, Country colleague);
}
中介者实现类
public class UnitedNationsSecurityCouncil extends UnitedNations {
private USA colleague1;
private Iraq colleague2;
public USA getColleague1() {
return colleague1;
}
public void setColleague1(USA colleague1) {
this.colleague1 = colleague1;
}
public Iraq getColleague2() {
return colleague2;
}
public void setColleague2(Iraq colleague2) {
this.colleague2 = colleague2;
}
public void declare(String message, Country colleague) {
if(colleague == colleague1) {
colleague2.getMessage(message);
} else {
colleague1.getMessage(message);
}
}
}
抽象成员类,构造函数中存在中介者
public abstract class Country {
protected UnitedNations mediator;
public Country(UnitedNations mediator) {
this.mediator = mediator;
}
}
成员类1
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);
}
}
成员类2
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);
}
}