Skip to content

Design Patterns

Chain of Responsibility

In the worst case, a request travels through all n handlers. So handling one request takes O(n) time — the time can grow with the number of handlers.

The idea, in plain English

Chain of responsibility passes a request down a line of people until someone can handle it. Think of an expense request going to your manager first. If it's too big, it moves up to the director, then the VP. Each person either deals with it or bumps it up the chain.

How it works

  1. 1You line up a series of handler objects. Each one knows which handler comes next.
  2. 2You hand the request to the first handler in line.
  3. 3Each handler asks 'can I handle this?' If yes, it deals with it. If no, it passes the request to the next handler in line.

When you'd use it

Use this when several objects might handle a request, but you don't know which one in advance. Examples: approval chains, event handling, or support-ticket escalation.

Common beginner mistakes

  • Always set the 'next' handler, or a request can silently get dropped instead of passing along.
  • Don't build a chain so long that requests take forever to reach the handler that can actually deal with them.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Manager approved $50
Director approved $500
VP approved $5000

Not sure this is the right topic? See the learning paths → or where this leads →