中介者模式(Mediator)定義:用一箇中介對象來封裝一系列的對象交互。中介者使各對象不須要顯示的相互引用,從而使其耦合鬆散,並且能夠獨立地改變它們之間的交互。java
類型:行爲型模式git
順口溜:中訪策備迭 觀模命狀職解github
我的感受,中介者模式是比較複雜的設計模式,想要真正掌握它還須要多多思考。設計模式
package com.amosli.dp.behavior.mediator; public class Client { public static void main(String[] args) { ConcreteMediator mediator = new ConcreteMediator(); ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator); mediator.setColleague1(colleague1); mediator.setColleague2(colleague2); colleague1.send(" hi,this is c1 "); colleague2.send(" hi,this is c2 "); } } package com.amosli.dp.behavior.mediator; public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } } package com.amosli.dp.behavior.mediator; public class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } public void send(String msg) { mediator.sendMsg(msg, this); } public void notify(String msg) { System.out.println("colleague1 getMsg:" + msg); } } package com.amosli.dp.behavior.mediator; public class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } public void send(String msg) { mediator.sendMsg(msg, this); } public void notify(String msg) { System.out.println("colleague2 get msg:" + msg); } } package com.amosli.dp.behavior.mediator; public class ConcreteMediator extends Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public void setColleague1(ConcreteColleague1 colleague1) { this.colleague1 = colleague1; } public void setColleague2(ConcreteColleague2 colleague2) { this.colleague2 = colleague2; } @Override void sendMsg(String msg, Colleague colleague) { if(colleague==colleague1){ colleague2.notify(msg); }else{ colleague1.notify(msg); } } } package com.amosli.dp.behavior.mediator; public abstract class Mediator { abstract void sendMsg(String msg,Colleague colleague); }
使用終結者模式的場合ide
能夠看出,中介對象主要是用來封裝行爲的,行爲的參與者就是那些對象,可是經過中介者,這些對象不用相互知道。呵呵~~~this
使用中介者模式的優勢:spa
1.下降了系統對象之間的耦合性,使得對象易於獨立的被複用。設計
2.提升系統的靈活性,使得系統易於擴展和維護。code
使用中介者模式的缺點:orm
中介者模式的缺點是顯而易見的,由於這個「中介「承擔了較多的責任,因此一旦這個中介對象出現了問題,那麼整個系統就會受到重大的影響。
本系列文章源碼地址,https://github.com/amosli/dp 歡迎Fork & Star !!