大話設計模式之中介者模式
阿新 • • 發佈:2018-08-29
brush 行為 imp script 依賴關系 sig 交互 轉化 核武器
中介者模式
用一個中介對象來封裝一系列對象的交互。中介者使各個對象不需要顯示的相互引用,從而使其耦合松散,而且可以獨立的改變他們之間的交互。
涉及到的角色描述
- Mediator:抽象中介者角色,定義了同事對象到中介者對象的接口。
- ConcreteMediator:具體中介者角色,它從具體的同事對象接收消息,向具體同事發出命令。
- Colleague:抽象同事角色,定義了中介者對象接口,它只知道中介者而不知道其他同事對象。
- ConcreteColleague:具體同事角色,每個具體同事類都知道自己在小範圍內的行為,而不知道它在大範圍內的目的。
優點
1、降低了類的復雜度,將一對多轉化成了一對一。
2、各個類之間的解耦。
3、符合迪米特原則。
缺點
中介者會龐大,變得復雜難以維護。
使用場景
1、系統中對象之間存在比較復雜的引用關系,導致它們之間的依賴關系結構混亂而且難以復用該對象。
2、想通過一個中間類來封裝多個類中的行為,而又不想生成太多的子類。
具體代碼實現
先定義抽象中介Mediator
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: 中介者接口 * @Date: created in 2018/8/28 * @Modified By: */ public interface UniteNations { void declare(String message,Country country); }
抽象同事類Colleague
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: 抽象國家類持有一個中介者對象 * @Date: created in 2018/8/28 * @Modified By: */ public abstract class Country { UniteNations uniteNations; Country(UniteNations uniteNations){ this.uniteNations = uniteNations; } }
具體同事1ConcreteColleague1
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: * @Date: created in 2018/8/28 * @Modified By: */ public class USA extends Country { USA(UniteNations uniteNations) { super(uniteNations); } public void declare(String message){ uniteNations.declare(message,this); } public void getMessage(String message){ System.out.println("美國獲得對方消息:"+message); } }
具體同事1ConcreteColleague2
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: * @Date: created in 2018/8/28 * @Modified By: */ public class Iraq extends Country { Iraq(UniteNations uniteNations) { super(uniteNations); } public void declare(String message){ uniteNations.declare(message,this); } public void getMessage(String message){ System.out.println("伊拉克獲得對方消息:"+message); } }
具體中介者
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: 具體中介者 * @Date: created in 2018/8/28 * @Modified By: */ public class UniteNationsSecurity implements UniteNations { private USA usa; private Iraq iraq; public void setUSA(USA usa){ this.usa=usa; } public void setIraq(Iraq iraq){ this.iraq=iraq; } @Override public void declare(String message, Country country) { if(country==usa){ iraq.getMessage(message); }else if(country==iraq){ usa.getMessage(message); } } }
客戶端
package com.chenpt.designModel.mediatorModel; /** * @Author: chen * @Description: * @Date: created in 2018/8/28 * @Modified By: */ public class MainTest { public static void main(String[] as){ UniteNationsSecurity security = new UniteNationsSecurity(); USA usa = new USA(security); Iraq iraq = new Iraq(security); security.setUSA(usa); security.setIraq(iraq); usa.declare("不準研制核武器,否則發動戰爭"); iraq.declare("我們沒有核武器,也不怕侵略"); } } //執行結果 伊拉克獲得對方消息:不準研制核武器,否則發動戰爭 美國獲得對方消息:我們沒有核武器,也不怕侵略
大話設計模式之中介者模式