- 中介者模式简介:
多个类之间的通讯方式封装成一个对象,只能,从这个对象转发给多个类。
- 从代码的角度来理解(特工与特工之间只能通过情况报站(MEDIATOR)来交换信息)
package mediator; //特工类 public abstract class ColleaugeAgent { //特工必须是相互是不能认识的,不能交流的,不能说话,只有,通过情报站,所以,每个特工都有情报站 private MediatorIn mediatorIn; public ColleaugeAgent(MediatorIn mediatorIn) { this.mediatorIn = mediatorIn; } protected MediatorIn getAgentOfLocation() { return mediatorIn; } }
- 特工A:
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:我被知道有任务了,但是,我不知道是谁通知我的"); } }
- 特工B:
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
时间: 2024-10-10 15:21:00