用一箇中介對象來封裝一系列的對象交互。中介使各對象之間不須要顯示的相互引用,從而使其耦合鬆散,並且能夠獨立的改變它們之間的交互。安全
「聯合國」就是世界上各個國家的一個「中介」,許多事情都不是國家之間直接交互,而是經過「安理會」等組織進行協商、投票等過程。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
伊拉克得到對方信息:不許研製核武器,不然要發動戰爭! 美國得到對方信息:咱們沒有核武器,也不怕侵略!