中介者模式(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 !!