design patterns ·

Chain of Responsibility

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

medium1hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

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.

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