码迷,mamicode.com
首页 > 其他好文 > 详细

从特工的角度来看设计模式之中介者模式

时间:2015-02-14 22:30:56      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

  转载请声明:http://www.cnblogs.com/courtier/p/4292201.html

  • 中介者模式简介:

       多个类之间的通讯方式封装成一个对象,只能,从这个对象转发给多个类。

       技术分享

  • 从代码的角度来理解(特工与特工之间只能通过情况报站(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

从特工的角度来看设计模式之中介者模式

标签:

原文地址:http://www.cnblogs.com/courtier/p/4292201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!