java之责任链模式

一、简介

责任链模式(Chain of Responsibility Pattern)是一种行为设计模式,它允许多个对象有机会处理一个请求。请求沿着处理者链传递,直到某个处理者决定处理此请求。

二、技术实现

2.1 Handler
java 复制代码
public interface Handler{
    void handle(Request req, Response resp, Chain chain);
}
2.2 Chain
java 复制代码
public class Chain{
   
    private List<Handler> handlers;
    
    private int index;

    public Chain(List<Handler> handlers){

         this.handlers = handlers;

    }

   
    public void next(Request req, Response resp){
        
        if (index + 1 < handlers.size()){

            handlers.get(index++).handle(req, resp, this);
         
        }

    }
}
2.3 Handler 实现
java 复制代码
public LogHandler implements Handler{

    @Override
    public void Handle (Request req, Response resp, Chain chain){
        long start = System.currentTimeStamps();
        chain.next(req,resp);
        log.info("request:{},response:{}, duration:{}",req, resp, System.currentTimeStamps() - start);         
    }
}
相关推荐
爱编程的鱼9 分钟前
OpenCV Python 绑定:原理与实战
c语言·开发语言·c++·python
这周也會开心16 分钟前
云服务器安装JDK、Tomcat、MySQL
java·服务器·tomcat
hrrrrb1 小时前
【Spring Security】Spring Security 概念
java·数据库·spring
小信丶1 小时前
Spring 中解决 “Could not autowire. There is more than one bean of type“ 错误
java·spring
sdgsdgdsgc1 小时前
Next.js企业级应用开发:SSR、ISR与性能监控方案
开发语言·前端·javascript
周杰伦_Jay2 小时前
【Java虚拟机(JVM)全面解析】从原理到面试实战、JVM故障处理、类加载、内存区域、垃圾回收
java·jvm
rit84324995 小时前
基于MATLAB的模糊图像复原
开发语言·matlab
fie88895 小时前
基于MATLAB的声呐图像特征提取与显示
开发语言·人工智能
程序员小凯6 小时前
Spring Boot测试框架详解
java·spring boot·后端
豐儀麟阁贵6 小时前
基本数据类型
java·算法