Skip to the guide

Chain of responsibility

IntermediatePattern7 pages

Chain of responsibility passes a request along a line of objects until one of them deals with it, so the sender never needs to know which one will. The 1994 book Design Patterns gives its intent as "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." Interviewers listen for what decides the order, and for when a table or a list is the better design.

A coin sorter with holes in a row

Think of a coin sorter, a sloping track with a row of holes in it. You drop a coin in at the top and it rolls down. Each hole asks whether this coin fits. A coin that fits drops through, and any other coin rolls on to the next hole. The track ends in a tray for coins that fit nowhere, such as a foreign one.

Whoever built the sorter chose the order of the holes, smallest first. Put the biggest hole first and every coin falls straight through it. A sorter for another country has different holes.

In code, the coin is an Expense, and each hole is a step behind the Approver interface, such as a LimitApprover that approves amounts up to its limit. Rolling on to the next hole is the call next.review(expense). The tray is NoOneLeft, the step at the end of every line. The person who built the sorter is ApprovalLines, which puts the steps in order, and a sorter for another country is a line for another team.