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);         
    }
}
相关推荐
C雨后彩虹2 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..2 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X2 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
SmartRadio3 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion3 小时前
QT5.7.0编译移植
开发语言·qt
rit84324994 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
元Y亨H4 小时前
Nacos - 服务发现
java·微服务
微露清风4 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi02274 小时前
Java趣闻
java
大、男人4 小时前
python之asynccontextmanager学习
开发语言·python·学习