microwind/ai-skills/chain-of-responsibility-pattern

Claude Code and agent skill by microwind/ai-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

将请求沿着处理者链进行传递,直到有处理者处理该请求

Install

npx vskill@latest install microwind/ai-skills/chain-of-responsibility-pattern

SKILL.md

Chain of Responsibility Pattern (责任链模式)

核心概念

Chain of Responsibility是一种Behavioral设计模式。

定义: 将请求沿着一个处理者链进行传递,直到有一个处理者处理该请求。它避免了发送者和接收者之间的紧耦合。

核心思想
  • 传递链: 请求从链的首端开始,逐个传递给处理者
  • 权责分离: 每个处理者关注自己能处理的请求类型
  • 灵活组合: 可以动态添加、移除或重新排列处理者
  • 自动降级: 如果一个处理者无法处理,自动传递给下一个

何时使用

触发条件
  1. 多个处理者,任意一个可以处理请求 - 如日志系统、身份验证、事件处理
  2. 处理者集合不固定 - 需要动态组织处理流程
  3. 想要解耦发起者和处理者 - 发起者不关心谁最终处理
  4. 请求有优先级或依赖关系 - 审批流、事件分发
  5. 处理过程涉及多个层级 - 如权限验证、异常处理链
不适合场景
  • ❌ 只有单一处理者的情况 - 直接调用即可
  • ❌ 需要并行处理所有请求 - 应该使用观察者模式
  • ❌ 处理顺序完全随意且无规律

基本结构

参与者
  1. Handler (处理者) - 定义处理请求的接口,包含对下一个处理者的引用
  2. ConcreteHandler (具体处理者) - 实现处理请求的逻辑,决定是否处理或传递给下一个
  3. Client (客户端) - 向链中的某个处理者提交请求
UML关系
┌─────────────────┐
│ Handler │
├─────────────────┤
│ - successor │
│ + handleRequest │
└─────────────────┘
△
│ implements
│
┌───┴───────────────────┐
│ │
┌───────────────────┐ ┌─────────────────┐
│ ConcreteHandler1 │ │ ConcreteHandler2 │
├───────────────────┤ ├─────────────────┤
│ + handleRequest() │ │ + handleRequest()│
└───────────────────┘ └─────────────────┘
Client → Handler Chain → Handler1 → Handler2 → Handler3
流程图
请求进入
↓
[Handler1能处理?] → 是 → 处理请求并返回
↓ 否
[Handler2能处理?] → 是 → 处理请求并返回
↓ 否
[Handler3能处理?] → 是 → 处理请求并返回
↓ 否
[还有下一个处理者?] → 是 → 传递给下一个
↓ 否
请求未处理 (返回null或异常)

实现方式对比

方法1: 经典链式实现 (基础)

特点: 最基础的职责链,处理者手动管理next引用

java
// Handler接口
abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler handler) {
this.successor = handler;
}
public abstract void handleRequest(Request request);
}
// 具体处理者
class ConcreteHandler1 extends Handler {
@Override
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println("Handler1 处理请求: " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
// 使用示例
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
handler1.setSuccessor(handler2);
handler1.handleRequest(request);
方法2: 动态链式实现 (流式构建)

特点: 使用Builder模式动态构建处理链

java
class ChainBuilder {
private Handler head;
private Handler tail;
public ChainBuilder add(Handler handler) {
if (head == null) {
head = tail = handler;
} else {
tail.setSuccessor(handler);
tail = handler;
}
return this;
}
public Handler build() {
return head;
}
}
// 使用示例
Handler chain = new ChainBuilder()
.add(new AuthenticationHandler())
.add(new AuthorizationHandler())
.add(new LoggingHandler())
.add(new ProcessingHandler())
.build();
chain.handleRequest(request);
方法3: 函数式链式实现

特点: 使用函数式编程,支持Lambda表达式

java
@FunctionalInterface
interface RequestHandler {
Result handle(Request request, RequestHandler next);
}
class FunctionalChain {
public static RequestHandler chain(List<RequestHandler> handlers) {
return (request, next) -> {
final RequestHandler[] current = {null};
for (int i = handlers.size() - 1; i >= 0; i--) {
final RequestHandler handler = handlers.get(i);
final RequestHandler finalNext = current[0];
current[0] = (req, n) -> handler.handle(req,
(r, fn) -> {
if (finalNext != null) {
return finalNext.handle(r, fn);
}
return new Result(false, "No handler");
});
}
return current[0].handle(request, next);
};
}
}
// 使用示例
RequestHandler chain = FunctionalChain.chain(Arrays.asList(
(req, next) -> req.type == 1 ? new Result(true, "handled") : next.handle(req, null),
(req, next) -> req.type == 2 ? new Result(true, "handled") : next.handle(req, null),
(req, next) -> new Result(false, "unhandled")
));
方法4: 事件驱动链 (异步处理)

特点: 基于事件总线,支持异步处理和并发

java
class EventDrivenChain {
private EventBus eventBus = new EventBus();
private List<EventHandler> handlers = new CopyOnWriteArrayList<>();
public void register(EventHandler handler) {
handlers.add(handler);
eventBus.register(handler);
}
public void process(Request request) {
eventBus.post(new RequestEvent(request));
}
static class EventHandler {
@Subscribe
public void handleRequest(RequestEvent event) {
// 异步处理请求
}
}
}
// 使用示例
EventDrivenChain chain = new EventDrivenChain();
chain.register(new ValidationHandler());
chain.register(new ProcessingHandler());
chain.register(new NotificationHandler());
chain.process(request);

8个真实使用场景

场景1: 日志系统 (Logging)

应用: Apache Commons Logging, SLF4J

java
// 日志处理链:ERROR -> WARN -> INFO -> DEBUG -> TRACE
abstract class LogHandler {
protected LogHandler nextHandler;
protected LogLevel level;
public void setNextHandler(LogHandler handler) {
this.nextHandler = handler;
}
public void log(LogLevel level, String message) {
if (this.level.getValue() <= level.getValue()) {
writeLog(message);
}
if (nextHandler != null) {
nextHandler.log(level, message);
}
}
protected abstract void writeLog(String message);
}
class ErrorHandler extends LogHandler {
public ErrorHandler() { this.level = LogLevel.ERROR; }
protected void writeLog(String msg) { System.err.println("[ERROR] " + msg); }
}
class WarnHandler extends LogHandler {
public WarnHandler() { this.level = LogLevel.WARN; }
protected void writeLog(String msg) { System.out.println("[WARN] " + msg); }
}
// 构建链
LogHandler errorHandler = new ErrorHandler();
LogHandler warnHandler = new WarnHandler();
errorHandler.setNextHandler(warnHandler);
场景2: Web请求处理 (Middleware)

应用: Spring Security Filter Chain, Express.js中间件

java
// Spring Security FilterChain
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
return http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.build(); // 内部构建责任链
}
}
// 中间件链: CORS → Authentication → Authorization → Logging
public class SecurityFilterChain {
private List<SecurityFilter> filters = new ArrayList<>();
public SecurityFilterChain addFilter(SecurityFilter filter) {
filters.add(filter);
return this;
}
public void doFilter(Request req, Response res) {
new FilterChainImpl(filters, 0).doFilter(req, res);
}
}
场景3: 审批工作流 (Approval Workflow)

应用: Alfresco工作流, 企业审批系统

java
// 审批流:员工 → 部门经理 → 总监 → CFO → CEO
abstract class ApprovalHandler {
protected ApprovalHandler nextApprover;
protected double approvalLimit;
public void setNextApprover(ApprovalHandler handler) {
this.nextApprover = handler;
}
public void handleRequest(ExpenseRequest request) {
if (request.getAmount() <= approvalLimit) {
approve(request);
} else if (nextApprover != null) {
nextApprover.handleRequest(request);
} else {
reject(request);
}
}
abstract void approve(ExpenseRequest request);
abstract void reject(ExpenseRequest request);
}
class ManagerApprover extends ApprovalHandler {
public ManagerApprover() { this.approvalLimit = 5000; }
void approve(ExpenseRequest req) { System.out.println("经理批准: " + req); }
void reject(ExpenseRequest req) { System.out.println("经理拒绝: " + req); }
}
场景4: 事件处理系统 (Event Processing)

应用: Swing事件处理, DOM事件冒泡

java
// GUI事件链: 按钮 → 容器 → 窗口
abstract class Component {
protected Component parent;
public void setParent(Component parent) {
this.parent = parent;
}
public void handleEvent(Event event) {
if (canHandle(event)) {
processEvent(event);
event.setProcessed(true);
}
if (!event.isProcessed() && parent != null) {
parent.handleEvent(event);
}
}
abstract boolean canHandle(Event event);
abstract void processEvent(Event event);
}
class Button extends Component {
boolean canHandle(Event event) { return event instanceof ClickEvent; }
void processEvent(Event event) { System.out.println("Button clicked"); }
}
场景5: 异常处理链 (Exception Handling)

应用: Java异常处理, 防御性编程

java
// 异常处理链: 业务异常 → IO异常 → 系统异常 → 默认
abstract class ExceptionHandler {
protected ExceptionHandler nextHandler;
public void setNextHandler(ExceptionHandler handler) {
this.nextHandler = handler;
}
public void handle(Exception ex) {
if (canHandle(ex)) {
processException(ex);
} else if (nextHandler != null) {
nextHandler.handle(ex);
} else {
System.err.println("未处理的异常: " + ex);
}
}
abstract boolean canHandle(Exception ex);
abstract void processException(Exception ex);
}
class DatabaseExceptionHandler extends ExceptionHandler {
boolean canHandle(Exception ex) { return ex instanceof SQLException; }
void processException(Exception ex) {
System.out.println("数据库异常重试or回滚");
}
}
场景6: 请求验证链 (Validation Chain)

应用: Bean Validation, 表单验证

java
// 验证链: 空值检查 → 格式检查 → 业务规则检查
abstract class Validator {
protected Validator nextValidator;
public void setNextValidator(Validator validator) {
this.nextValidator = validator;
}
public ValidationResult validate(User user) {
ValidationResult result = doValidate(user);
if (!result.isValid()) {
return result;
}
if (nextValidator != null) {
return nextValidator.validate(user);
}
return new ValidationResult(true);
}
abstract ValidationResult doValidate(User user);
}
class EmailValidator extends Validator {
ValidationResult doValidate(User user) {
if (user.email == null || !user.email.contains("@")) {
return new ValidationResult(false, "Invalid email");
}
return new ValidationResult(true);
}
}
场景7: 消息处理管道 (Message Pipeline)

应用: 消息队列处理, 数据流处理

java
// 消息处理链: 反序列化 → 加密 → 业务处理 → 序列化
abstract class MessageHandler {
protected MessageHandler next;
public void setNext(MessageHandler handler) {
this.next = handler;
}
public final Message handle(Message message) {
Message result = process(message);
if (next != null && result != null) {
return next.handle(result);
}
return result;
}
abstract Message process(Message message);
}
class EncryptionHandler extends MessageHandler {
Message process(Message msg) {
msg.payload = encrypt(msg.payload);
return msg;
}
}
class BusinessHandler extends MessageHandler {
Message process(Message msg) {
// 执行业务逻辑
return msg;
}
}
场景8: 路由和调度 (Routing)

应用: 请求路由, 任务调度

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
51
Repository forks
13
7-day trend score
20

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/microwind/ai-skills/chain-of-responsibility-pattern/badge)](https://verified-skill.com/skills/microwind/ai-skills/chain-of-responsibility-pattern)

Something wrong with this skill or its page? Tell us.