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

职责链模式(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);
}

 

posted @ 2015-10-07 11:35  郁闷紫番薯  阅读(248)  评论(0编辑  收藏  举报