Skip to main content

What It Is

The Chain of Responsibility pattern passes a request along a chain of handlers. Each handler either deals with the request or hands it to the next one. The sender only knows the first link — never who will actually solve it.


Example: A Support Line

A problem enters at the chat bot. What the bot cannot fix goes to tech support; what tech support cannot fix goes to the manager, who handles everything that arrives.

The next link is typed Handler | undefined, so the last link simply has none. this.next?.handle(problem) calls it only when it is there.

Pass it on until someone can

no internet travels one step and stops at tech support; the refund request travels the whole chain to the manager. The caller wrote the same one line both times.

Prompt
Write a TypeScript program with a Chain of Responsibility: a Handler class with a name, a canFix function and an optional next handler. Build a support chain of chat bot, tech support and manager (who fixes everything). Send one problem the middle link can fix and one that travels to the manager, printing each step.
Output: TypeScript file and captured output
Pass it on until someone can

When to Use It

Use it when several parties might handle a request and the right one is not known in advance — support escalation, middleware, event handling, approval workflows.

Skip it when the handler is always known — call it directly. A chain with one link, or one that always ends at the same link, is a plain function call in costume.


Pros and Cons

Pros: sender and receivers are decoupled; links can be added, removed and reordered freely; each handler stays small.

Cons: no guarantee anyone handles the request — a broken chain swallows it silently; following a request through many links makes debugging slower.