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

设计模式(责任链模式)

时间:2015-06-13 09:45:05      阅读:87      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!