design patterns · behavioral

Chain of Responsibility

Passes a request along a chain of handlers, each deciding to process it or pass it to the next handler.

mediumbehavioral1h
Ask GPTConfidence

Pattern

Overview

Intent

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Real-World Analogy

Customer support escalation - L1 agent tries to help; if unable, escalates to L2; if still unable, escalates to Manager.

When multiple objects might handle a request and you want to avoid hardcoding which one does it, link them in a chain. The request travels down the chain until something handles it.

Each handler has a reference to the next handler in the chain. The handler either processes the request or forwards it to next. Handlers are assembled into a chain by the client or a builder.

When to use

Request processing pipelines, middleware (auth → logging → authorization), event handling systems, expense approval workflows - any case where multiple objects might handle a request.

When not to

When exactly one specific handler must always process the request. When the chain is always length 1.

Participants

HandlerConcreteHandlerClient

Key Insights

  • Handlers decide independently whether to process or forward - no central coordinator
  • Chain can be built dynamically at runtime
  • Spring Security filter chains are a real-world Chain of Responsibility
  • Unlike Decorator (always delegates), Chain handlers may consume the request and not forward