首页 > 其他 > 详细

设计模式(责任链模式)

时间:2015-06-13 09:42:48      阅读:127      评论:0      收藏:0      [点我收藏+]

当多个对象都存在处理请求的情况时,通过构造一条处理责任链,将请求者和处理者解耦。这样具体的处理方式和处理顺序都可以灵活调整。

代码如下:

  • Handler
public abstract class Handler {
    public Handler next;
    
    public Handler setNext(Handler handler){
        this.next = handler;
        return this;
    }
    
    public abstract void doAction();
}
  • HandlerOneImpl
public class HandlerOneImpl extends Handler {

    @Override
    public void doAction() {
        if(null != this.next){
            this.next.doAction();
        }
        
        System.out.println("HandlerOneImpl");
    }
}
  • HandlerTwoImpl
public class HandlerTwoImpl extends Handler {

    @Override
    public void doAction() {
        if(null != this.next){
            this.next.doAction();
        }
        
        System.out.println("HandlerTwoImpl");
    }
}
  • APP 测试类
public class App {

    public static void main(String[] args) {
        HandlerOneImpl one = new HandlerOneImpl();
        one.setNext(new HandlerTwoImpl()).doAction();
    }
}
  • 输出结果
HandlerTwoImpl
HandlerOneImpl

设计模式(责任链模式)

原文:http://www.cnblogs.com/Fredric-2013/p/4572956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!