java设计模式-责任链模式

什么是责任链模式:
将请求同一类资源的请求对象练成一条链,所提交的请求到某一个链节,如果该链节能处理则不必要往下传,不然则继续传到下一个对象链接去处理。

开发中常见的场景:
1.springmvc的拦截器
2.java中,异常处理机制,抛出异常
3.javascript的事件冒泡机制

责任链例子:
这里的场景是实现一个拦截器demo,所限当然是定义我们的拦截器,然后,使用时,就继承它


/**
 * 定义一个拦截器
 * @author liuxg
 * @date 2016年5月27日 下午6:01:27
 */
public abstract class Interceptor {

    protected  Interceptor nextChain ;
    public void setNextChain(Interceptor nextChain) {
        this.nextChain = nextChain;
    }

    public abstract void  beginIntecept(String condition);


}

class Interceptor1 extends Interceptor{

    @Override
    public void beginIntecept(String condition) {

        if ("interceptor1".equals(condition)) {
            System.out.println("拦截器到interceptor1");
        }else{
            System.out.println("interceptor1无法处理,到下一个拦截器");
            nextChain.beginIntecept(condition);
        }
    }

}

class Interceptor2 extends Interceptor{

    @Override
    public void beginIntecept(String condition) {
        if ("interceptor2".equals(condition)) {
            System.out.println("拦截器到interceptor2");
        }else{
            System.out.println("interceptor2无法处理,到下一个拦截器");
            nextChain.beginIntecept(condition);
        }
    }

}
class Interceptor3 extends Interceptor{

    @Override
    public void beginIntecept(String condition) {
        if ("interceptor3".equals(condition)) {
            System.out.println("拦截器到interceptor3");
        }else{
            System.out.println("interceptor3无法处理,到下一个拦截器");
            nextChain.beginIntecept(condition);
        }
    }

}

客户端可以传递一个条件字符串,所有跟其中一个拦截器匹配,则该拦截器处理,如果不行,则传递到下一个拦截器处理

public class Client {

    public static void main(String[] args) {
        Interceptor interceptor1 = new Interceptor1();
        Interceptor interceptor2 = new Interceptor2();
        Interceptor interceptor3 = new Interceptor3();

        interceptor1.setNextChain(interceptor2);
        interceptor2.setNextChain(interceptor3);

        interceptor1.beginIntecept("interceptor3");//处理条件

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值