1. 概念
用一个中介对象来封装一系列的对象交互。中介者使对象不需要显式的相互引用,而且可以独立的改变它们之间的交互。
2. 创建抽象中介者类
/**
* @author zlc
* @created 2017/12/24
* Mediator中介者
*/
public abstract class UnitedNations {
public abstract void sendDeclare(String msg, Country country);
}
3. 创建抽象Colleague类
/**
* @author zlc
* @created 2017/12/24
*/
public abstract class Country {
protected UnitedNations mediator;
public Country(UnitedNations mediator){
this.mediator = mediator;
}
public abstract void sendDeclare(String message);
public abstract void getMessage(String message);
}
4. 创建具体Colleague类
1.
/**
* @author zlc
* @created 2017/12/24
*/
public class USA extends Country{
public USA(UnitedNations mediator) {
super(mediator);
}
@Override
public void sendDeclare(String message) {
mediator.sendDeclare(message,this);
}
@Override
public void getMessage(String message) {
System.out.println("美国获得对方消息:"+message);
}
}
2.
/**
* @author zlc
* @created 2017/12/24
*/
public class Iraq extends Country{
public Iraq(UnitedNations mediator) {
super(mediator);
}
@Override
public void sendDeclare(String message) {
mediator.sendDeclare(message,this);
}
@Override
public void getMessage(String message) {
System.out.println("伊拉克获得对方消息:"+message);
}
}
5.创建具体中介者类
/**
* @author zlc
* @created 2017/12/24
*/
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 sendDeclare(String msg, Country country) {
if(country instanceof USA){
colleague2.getMessage(msg);
}else if(country instanceof Iraq){
colleague1.getMessage(msg);
}
}
}
6. 测试类
@org.junit.Test
public void test(){
//创建具体中介者
UnitedNationsSecurityCouncil unsc = new UnitedNationsSecurityCouncil();
// 让具体对象认识中介者
USA c1 = new USA(unsc);
Iraq c2 = new Iraq(unsc);
//让中介者认识各个具体的对象
unsc.setColleague1(c1);
unsc.setColleague2(c2);
//具体对象发送消息都是通过中介者转发的
c1.sendDeclare("不准研制核武器,否则发动战争");
c2.sendDeclare("我们没有核武器,也不怕侵略");
}
7.小结
中介者的出现减少了各个Colleague的耦合,使得可以独立的改变和复用各个Colleague和Mediator,优点来自集中控制,缺点也是。