标签:
多个类之间的通讯方式封装成一个对象,只能,从这个对象转发给多个类。
package mediator; //特工类 public abstract class ColleaugeAgent { //特工必须是相互是不能认识的,不能交流的,不能说话,只有,通过情报站,所以,每个特工都有情报站 private MediatorIn mediatorIn; public ColleaugeAgent(MediatorIn mediatorIn) { this.mediatorIn = mediatorIn; } protected MediatorIn getAgentOfLocation() { return mediatorIn; } }
package mediator; //特工A public class ColleaugeAgentA extends ColleaugeAgent{ public ColleaugeAgentA(MediatorIn mediatorIn) { super(mediatorIn); // TODO Auto-generated constructor stub } //我想去通知特工B public void notifyB(ColleaugeAgentB agentB) { //得到情报站,然后,给情报 getAgentOfLocation().notifyOtheragent(agentB); } public void getMsg() { System.out.println("A:我被知道有任务了,但是,我不知道是谁通知我的"); } }
package mediator; //特工A public class ColleaugeAgentB extends ColleaugeAgent{ public ColleaugeAgentB(MediatorIn mediatorIn) { super(mediatorIn); // TODO Auto-generated constructor stub } //我想去通知特工A public void notifyA(ColleaugeAgentA agentA) { //得到情报站,然后,给情报 getAgentOfLocation().notifyOtheragent(agentA); } public void getMsg() { System.out.println("B:我被知道有任务了,但是,我不知道是谁通知我的"); } }
package mediator; public interface MediatorIn { //通知到特工类 void notifyOtheragent(ColleaugeAgent colleaugeAgent); }
package mediator; //情报站必须持有特工名单,不然,怎么通知呢? public class ConcreteMediator implements MediatorIn{ private ColleaugeAgentA colleaugeAgentA; private ColleaugeAgentB colleaugeAgentB; public void setColleaugeAgentA(ColleaugeAgentA colleaugeAgentA) { this.colleaugeAgentA = colleaugeAgentA; } public void setColleaugeAgentB(ColleaugeAgentB colleaugeAgentB) { this.colleaugeAgentB = colleaugeAgentB; } //通知其他特工 @Override public void notifyOtheragent(ColleaugeAgent colleaugeAgent) { // TODO Auto-generated method stub if ( colleaugeAgent instanceof ColleaugeAgentA) { colleaugeAgentB.getMsg(); } else { colleaugeAgentA.getMsg(); } } }
(源代码:https://github.com/aliencool/Design-Pattrn/tree/master/mediator)
中介者模式是GOF经典模式之一,主要用于反射的INVOKE
标签:
原文地址:http://www.cnblogs.com/courtier/p/4292201.html