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

大话设计模式笔记 职责链模式 中介者模式

时间:2015-10-07 12:00:39      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

技术分享

 

优点:当客户提交一个请求是,请求是沿链传递直至有一个ConcreteHandler对象负责处理它。

接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可以简化对象的相互连接。

 

 

中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。

 

技术分享

 

package mediator;

public abstract class Colleague {
    protected Mediator mediator;
    
    public Colleague(Mediator mediator) {
        super();
        this.mediator = mediator;
    }
    
    public void send(String message) {
        mediator.send(message, this);
    }
    
    public void notify(String message) {
        System.out.println(this.toString()+" message:"+message);
    }
}

 

package mediator;

public class ConcreteColleagueA extends Colleague {

    public ConcreteColleagueA(Mediator mediator) {
        super(mediator);
    }

}

 

package mediator;

public class ConcreteColleagueB extends Colleague {

    public ConcreteColleagueB(Mediator mediator) {
        super(mediator);
    }

    public static void main(String[] args) {
        ConcreteMediator concreteMediator=new ConcreteMediator();
        
        ConcreteColleagueA a=new ConcreteColleagueA(concreteMediator);
        ConcreteColleagueB b=new ConcreteColleagueB(concreteMediator);
        concreteMediator.setColleagueA(a);
        concreteMediator.setColleagueB(b);
        a.send("from a to b");
        b.send("from b to a");
    }
}

 

package mediator;

public class ConcreteMediator extends Mediator {

    @Override
    public void send(String message, Colleague colleague) {
        if (colleague == colleagueA) {
            colleagueB.notify(message);
        } else {
            colleagueA.notify(message);
        }
    }

}

 

package mediator;

public abstract class Mediator {

    protected ConcreteColleagueA colleagueA;
    protected ConcreteColleagueB colleagueB;

    public void setColleagueA(ConcreteColleagueA colleagueA) {
        this.colleagueA = colleagueA;
    }

    public void setColleagueB(ConcreteColleagueB colleagueB) {
        this.colleagueB = colleagueB;
    }

    public abstract void send(String message, Colleague colleague);
}

 

大话设计模式笔记 职责链模式 中介者模式

标签:

原文地址:http://www.cnblogs.com/linkarl/p/4858442.html

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