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

设计模式之职责链模式

时间:2015-07-18 00:27:02      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

职责链模式

使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合。将系统连成一条线,并沿着这条线传递请求,直到有一个对象处理他为止。

Handler

package com.hml.responsiblity;

public abstract class Handler {
    
    protected Handler successor;

    public Handler getSuccessor() {
        return successor;
    }

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    
    public abstract void handleRequest(int num);

}

Handler1

package com.hml.responsiblity;

public class Handler1 extends Handler {

    @Override
    public void handleRequest(int num) {
        if (num < 10) {
            System.out.println(num);
        }else {
            successor.handleRequest(num);
        }
    }

}

Handler2

package com.hml.responsiblity;

public class Handler2 extends Handler {

    @Override
    public void handleRequest(int num) {
        if (num < 30) {
            System.out.println(num);
        }else {
            successor.handleRequest(num);
        }
    }

}

Handler3

package com.hml.responsiblity;

public class Handler3 extends Handler {

    @Override
    public void handleRequest(int num) {
        if (num > 30) {
            System.out.println(num);
        }else {
            successor.handleRequest(num);
        }
    }

}

Test

package com.hml.responsiblity;

public class Test {

    public static void main(String[] args) {
        Handler h1 = new Handler1();
        Handler h2 = new Handler2();
        Handler h3 = new Handler3();
        
        h1.setSuccessor(h2);
        h2.setSuccessor(h3);
        
        h1.handleRequest(1);
        h1.handleRequest(13);
    }
}

职责链的好处是一个请求沿着一条链传递,直到有一个对象处理。避免了请求的发送者和接受者之间的耦合。

设计模式之职责链模式

标签:

原文地址:http://www.cnblogs.com/heml/p/4655904.html

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