责任链模式怎么写

本文详细介绍了责任链模式在拦截器设计中的应用,通过具体实现展示了如何使用拦截器处理请求和响应,包括BridgeInterceptor、RetryAndFollowInterceptor和CacheInterceptor三个示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拦截器接口

public interface Interceptor {
    String interceptor(Chain chain);

    interface Chain{
        String request();
        String proceed(String request);
    }
}

实现3个拦截器

public class BridgeInterceptor implements Interceptor{

    @Override
    public String interceptor(Chain chain) {
        System.out.println("执行 BridgeInterceptor 拦截器之前代码");
        String proceed = chain.proceed(chain.request());
        System.out.println("执行 BridgeInterceptor 拦截器之后代码 得到最终数据:"+proceed);
        return proceed;
    }
}

public class RetryAndFollowInterceptor implements Interceptor {

    @Override
    public String interceptor(Chain chain) {
        System.out.println("执行 RetryAndFollowInterceptor 拦截器之前代码");
        String proceed = chain.proceed(chain.request());
        System.out.println("执行 RetryAndFollowInterceptor 拦截器之后代码 得到最终数据:" + proceed);
        return proceed;
    }
}

public class CacheInterceptor implements Interceptor {

    @Override
    public String interceptor(Chain chain) {
        System.out.println("执行 CacheInterceptor 最后一个拦截器 返回最终数据");
        return "success";
    }
}

实现chain接口

public class RealInterceptorChain implements Interceptor.Chain {

    private List<Interceptor> interceptors;
    private int index;
    private String request;

    public RealInterceptorChain(List<Interceptor> interceptors, int index, String request) {
        this.interceptors = interceptors;
        this.index = index;
        this.request = request;
    }

    @Override
    public String request() {
        return request;
    }

    @Override
    public String proceed(String request) {
        if (index >= interceptors.size()) return null;
        RealInterceptorChain next = new RealInterceptorChain(interceptors,index+1,request);
        Interceptor interceptor = interceptors.get(index);
        return interceptor.interceptor(next);
    }
}

下面是测试代码

public class Test {

    public static void main(String args[]) {

        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new BridgeInterceptor());
        interceptors.add(new RetryAndFollowInterceptor());
        interceptors.add(new CacheInterceptor());

        RealInterceptorChain request = new RealInterceptorChain(interceptors, 0, "request");
        request.proceed("request");
    }
}

输出结果是:

执行 BridgeInterceptor 拦截器之前代码
执行 RetryAndFollowInterceptor 拦截器之前代码
执行 CacheInterceptor 最后一个拦截器 返回最终数据
执行 RetryAndFollowInterceptor 拦截器之后代码 得到最终数据:success
执行 BridgeInterceptor 拦截器之后代码 得到最终数据:success

 

重点:

每个拦截器的

chain.proceed()方法前是对请求的处理,之后是对返回的处理。这个是责任链模式的关键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值