用一个中介对象来封装一系列的对象交互。中介使各对象之间不须要显示的相互引用,从而使其耦合松散,并且能够独立的改变它们之间的交互。安全
“联合国”就是世界上各个国家的一个“中介”,许多事情都不是国家之间直接交互,而是经过“安理会”等组织进行协商、投票等过程。ide
/** * 联合国机构 * Created by callmeDevil on 2019/12/15. */ public abstract class UnitedNations { // 声明 public abstract void declare(String message, Country colleague); }
/** * 国家(至关于Colleague类) * Created by callmeDevil on 2019/12/15. */ public abstract class Country { protected UnitedNations mediator; public Country(UnitedNations mediator){ this.mediator = mediator; } }
/** * 美国(至关于 ConcreteColleague1 类) * Created by callmeDevil on 2019/12/15. */ 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); } }
/** * 伊拉克(至关于 ConcreteColleague2 类) * Created by callmeDevil on 2019/12/15. */ 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); } }
/** * 联合国安全理事会 * Created by callmeDevil on 2019/12/15. */ public class UnitedNationsSecurityCouncil extends UnitedNations{ // 美国 private USA colleague1; // 伊拉克 private Iraq colleague2; // 省略 get set @Override public void declare(String message, Country colleague) { // 重写声明方法,实现了两个对象之间的通讯 if (colleague == colleague1) { colleague2.getMessage(message); } else { colleague1.getMessage(message); } } }
public class Test { 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("咱们没有核武器,也不怕侵略!"); } }
运行结果this
伊拉克得到对方信息:不许研制核武器,不然要发动战争! 美国得到对方信息:咱们没有核武器,也不怕侵略!