中介者模式
用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
Mediator
package com.hml.mediator; public interface Mediator { public void send(String message, Colleague colleague); }
ConcreateMediator
package com.hml.mediator; public class ConcreateMediator implements Mediator { private Colleague colleague1; private Colleague colleague2; public Colleague getColleague1() { return colleague1; } public void setColleague1(Colleague colleague1) { this.colleague1 = colleague1; } public Colleague getColleague2() { return colleague2; } public void setColleague2(Colleague colleague2) { this.colleague2 = colleague2; } public void send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.notifyMessage(message); }else { colleague1.notifyMessage(message); } } }
Colleague
package com.hml.mediator; public abstract class Colleague { private Mediator mediator; public Mediator getMediator() { return mediator; } public void setMediator(Mediator mediator) { this.mediator = mediator; } public abstract void notifyMessage(String message); public abstract void sendMessage(String messege); }
ConcreateColleague1
package com.hml.mediator; public class ConcreateColleague1 extends Colleague { @Override public void notifyMessage(String message) { System.out.println("ConcreateColleague1:" + message); } @Override public void sendMessage(String messege) { getMediator().send(messege, this); } }
ConcreateColleague2
package com.hml.mediator; public class ConcreateColleague2 extends Colleague { @Override public void notifyMessage(String message) { System.out.println("ConcreateColleague2:" + message); } @Override public void sendMessage(String messege) { getMediator().send(messege, this); } }
Test
package com.hml.mediator; public class Test { public static void main(String[] args) { ConcreateMediator mediator = new ConcreateMediator(); Colleague colleague1 = new ConcreateColleague1(); colleague1.setMediator(mediator); // 同事认识中介 Colleague colleague2 = new ConcreateColleague2(); colleague2.setMediator(mediator); // 同事认识中介 mediator.setColleague1(colleague1); // 中介认识同事 mediator.setColleague2(colleague2); // 中介认识同事 colleague1.sendMessage("你吃饭了吗?"); // 通信 colleague2.sendMessage("没有,你请客吗?"); // 通信 } }
类图
中介者模式很容易在系统中使用,但是也很容易被误用,当系统中出现了多对多交互复杂的群时,不要急于使用中介者模式,而要反复的思考系统的设计是否合理。中介者模式一般应用于一组定义良好但是通信复杂的方式进行通信的场合。