中介者模式
用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式UML图
中介者模式代码
package com.roc.mediator; /** * 抽象中介者类 * @author liaowp * */ public abstract class Mediator { public abstract void send(String message,Colleague colleague); }
package com.roc.mediator; public class ConcreteMediator extends Mediator{ private Colleague1 colleague1; private Colleague2 colleague2; public void setColleague1(Colleague1 colleague1) { this.colleague1 = colleague1; } public void setColleague2(Colleague2 colleague2) { this.colleague2 = colleague2; } public void send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); }else{ colleague1.Notify(message); } } }
package com.roc.mediator; /** * 抽象同事类 * @author liaowp * */ public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator){ this.mediator=mediator; } }
package com.roc.mediator; public class Colleague1 extends Colleague{ public Colleague1(Mediator mediator) { super(mediator); } public void send(String message){ mediator.send(message, this); } public void Notify(String message){ System.out.println("同事1得到消息:"+message); } }
package com.roc.mediator; public class Colleague2 extends Colleague{ public Colleague2(Mediator mediator) { super(mediator); } public void send(String message){ mediator.send(message, this); } public void Notify(String message){ System.out.println("同事2得到消息:"+message); } }
package com.roc.mediator; /** * 中介者模式 * @author liaowp * */ public class Client { public static void main(String[] args) { ConcreteMediator mediator=new ConcreteMediator(); Colleague1 colleague1=new Colleague1(mediator); Colleague2 colleague2=new Colleague2(mediator); mediator.setColleague1(colleague1); mediator.setColleague2(colleague2); colleague1.send("最近还好吗?"); colleague2.send("还不错"); } }
中介者模式适用场景
-
一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解。
-
一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。
-
想定制一个分布在多个类中的行为,而又不想生成太多的子类。
- 一般应用于一组对象以定义良好但是复杂的方式进行通信的场合。