# Chain of Responsibility PatternWho signs a 3,000 expense? Learn how the Chain of Responsibility pattern lets a request find its own handler, with diagrams, Java code, servlet filters, and a narrated video.

You've just booked a flight to a conference in Lisbon. It cost 3,000, and now someone has to
approve the expense. But who? Your team lead can sign anything up to 1,000, your manager up to
5,000, the director up to 25,000. You shouldn't have to know any of that: you want to press
**Submit** and have the request find the right person on its own. That's exactly what the
**Chain of Responsibility pattern** does, and its whole idea fits in five words: *handle it, or
hand it on*.

{{< lesson-video youtube="o9cJeEOGy1o" title="Chain of Responsibility Pattern" >}}

Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article
follows it section by section, with diagrams, a little extra depth, and the complete code.

## Who signs this?

One request, several possible receivers, each with different powers:

```mermaid {alt="A 3,000 flight expense could go to the team lead, who signs up to 1,000, the manager, who signs up to 5,000, or the director, who signs up to 25,000; the sender doesn't know which one should handle it." caption="One request, several possible receivers. The sender shouldn't have to pick."}
flowchart TD
  E["flight to Lisbon<br/>3,000"] -.->|"?"| L["Team lead<br/>up to 1,000"]
  E -.->|"?"| M["Manager<br/>up to 5,000"]
  E -.->|"?"| D["Director<br/>up to 25,000"]
  class E hl
  class L c1
  class M c2
  class D c4
```

The person who submits the expense shouldn't need a map of the org chart and everyone's signing
limits. The request should **find its own handler**.

## Vocabulary: calling customer support

You already know this pattern from calling customer support. You dial one number, and the
**front desk** picks up. Your app crashes on login. The front desk can reset passwords, but not
this, so they pass you on to a **specialist**. The specialist handles billing, but this is a real
bug, so it goes one step further, to an **engineer**, who fixes it.

```mermaid {alt="Sequence: the caller dials one number and reaches the front desk; the front desk can't fix the crash and passes it to the specialist; the specialist passes it to the engineer; the engineer fixes it and answers the caller." caption="You dial one number. The desks decide among themselves who answers."}
sequenceDiagram
  actor U as You
  participant F as Front desk
  participant S as Specialist
  participant E as Engineer
  U->>F: "app crashes on login"
  Note over F: passwords only: pass it on
  F->>S: same ticket
  Note over S: billing only: pass it on
  S->>E: same ticket
  E-->>U: fixed
```

Notice what you did: you dialed **one** number, and you never chose who would answer. That gives
us the pattern's four words:

| Word | Meaning | In the support call |
|---|---|---|
| **Request** | the thing that travels along the chain | the ticket "app crashes on login" |
| **Handler** | deals with the request, or passes it on | front desk, specialist, engineer |
| **Next** (successor) | the handler a handler passes to | front desk → specialist → engineer |
| **Sender** (client) | sends the request; knows only the first handler | you, dialing one number |

## The obvious way: an if/else ladder

Back to expenses. The obvious first version is one method in an expense service, with a ladder of
`if` and `else`: up to 1,000, call the team lead; up to 5,000, the manager; up to 25,000, the
director. Anything bigger throws an exception, because nobody can approve it.

```java
class ExpenseService {
    void approve(Expense e) {
        if (e.amount() <= 1_000) {
            teamLead.approve(e);
        } else if (e.amount() <= 5_000) {
            manager.approve(e);
        } else if (e.amount() <= 25_000) {
            director.approve(e);
        } else {
            throw new IllegalStateException("nobody can approve " + e);
        }
    }
}
```

```mermaid {alt="Decision ladder inside ExpenseService: if the amount is up to 1,000 the team lead approves, else if up to 5,000 the manager, else if up to 25,000 the director, else an IllegalStateException is thrown." caption="The sender holds a ladder of every receiver and their rules."}
flowchart TD
  A{"amount ≤ 1,000?"} -->|yes| L["teamLead.approve(e)"]
  A -->|no| B{"amount ≤ 5,000?"}
  B -->|yes| M["manager.approve(e)"]
  B -->|no| C{"amount ≤ 25,000?"}
  C -->|yes| D["director.approve(e)"]
  C -->|no| X["IllegalStateException"]
  class L c1
  class M c2
  class D c4
  class X bad
```

It's short, it's readable, and it works. For now. It's the right first version, the way a
receptionist's cheat sheet of who handles what is fine on day one.

## Why it breaks: the ladder grows, and the sender knows everyone

Then the rules start arriving. Finance wants a **fraud check** that runs before anyone signs.
**Trips under 2,000** should go to the travel desk. And when the **manager is on vacation**, the
director signs instead. Each rule is another rung on the same ladder, in the same method:

```java
void approve(Expense e) {
    if (fraudCheck.looksSuspicious(e)) {
        fraudTeam.review(e);
    } else if (e.isTravel() && e.amount() <= 2_000) {
        travelDesk.approve(e);
    } else if (e.amount() <= 1_000) {
        teamLead.approve(e);
    } else if (e.amount() <= 5_000 && !manager.onVacation()) {
        manager.approve(e);
    } else if (e.amount() <= 25_000) {
        director.approve(e);
    } else {
        throw new IllegalStateException("nobody can approve " + e);
    }
}
```

And the **order of the rungs matters**. Move the fraud check down one line, and suspicious trips
get approved by the travel desk before anyone looks at them. Look at what the sender knows now:
every approver, every limit, and the exact order to ask them in.

```mermaid {alt="ExpenseService, the sender, points at five receivers and knows each one's position and rule: fraudTeam first, travelDesk second for trips under 2,000, teamLead third up to 1,000, manager fourth up to 5,000 when not on vacation, director fifth up to 25,000." caption="The sender knows every approver, every limit, and the order."}
flowchart LR
  S["ExpenseService<br/>(the sender)"] --> F["1st: fraudTeam"]
  S --> T["2nd: travelDesk<br/>trips under 2,000"]
  S --> L["3rd: teamLead<br/>up to 1,000"]
  S --> M["4th: manager<br/>up to 5,000, not on vacation"]
  S --> D["5th: director<br/>up to 25,000"]
  class S bad
  class F c3
  class T c6
  class L c1
  class M c2
  class D c4
```

And when another department wants a different order? You **copy the whole ladder**, and now two
copies drift apart. None of these rules can be tested on its own, either: to test the travel-desk
rule you have to get past the fraud check first. (When one rule change means editing several
copies like this, you're looking at [Shotgun Surgery](/code-smells/shotgun-surgery/); a
method that keeps growing rungs is on its way to a [Long Method](/code-smells/long-method/).)

> The problem isn't the `if` statements. **The sender knows too much.**

## The key insight: handle it, or hand it on

Here's the key insight. Give every approver the **same small job**: look at the request, and
**handle it, or hand it on** to the next one. Each handler knows only *its own rule* and *one
neighbor*, and the sender knows only the **first link** in the chain.

```mermaid {alt="Chain: the sender passes the 3,000 expense to TeamLead only; TeamLead, whose limit is 1,000, hands it on to Manager; Manager, up to 5,000, handles it and the request stops; Director never sees it." caption="Each link knows its own rule and its next link. The sender knows only the first."}
flowchart TD
  S["sender"] -->|"3,000"| L["TeamLead<br/>up to 1,000"]
  L -->|"too big:<br/>hand it on"| M["Manager<br/>up to 5,000"]
  M -.->|"never reached"| D["Director<br/>up to 25,000"]
  M --> OK(["signed:<br/>the request stops"])
  class S c6
  class L c1
  class M c2
  class D muted
  class OK good
```

Watch the flight travel. The team lead looks at 3,000: too big for me, so it goes on. The manager
looks: that's mine. Signed, and the request stops there.

And because the chain is **built from the outside**, you can change its shape. Put a fraud check
at the front, and nobody else changes: not the sender, and not the other handlers.

```mermaid {alt="Before and after: the chain TeamLead, Manager, Director becomes FraudCheck, TeamLead, Manager, Director by adding one link at the front; the sender and the existing handlers are unchanged." caption="Adding a link is configuration, not surgery."}
flowchart LR
  subgraph BEFORE["Before"]
    direction TB
    S1["sender"] --> L1["TeamLead"] --> M1["Manager"] --> D1["Director"]
  end
  subgraph AFTER["After: one new link"]
    direction TB
    S2["sender (unchanged)"] --> F2["FraudCheck"] --> L2["TeamLead"] --> M2["Manager"] --> D2["Director"]
  end
  BEFORE ~~~ AFTER
  class S1,S2 c6
  class F2 c3
  class L1,L2 c1
  class M1,M2 c2
  class D1,D2 c4
```

> **Handle it, or hand it on.**

## Building it in Java

We start with an abstract class, `ExpenseHandler`. It holds one field: the **next** handler in the
chain. A method called `linkTo` sets that field and returns the handler you just linked, so you
can chain the calls. Then the heart of the pattern, `handle`: if I can handle it, I process it.
Otherwise, if there is a next handler, I pass it on. And if there's nobody left, fail loudly.

```java
abstract class ExpenseHandler {
    private ExpenseHandler next;

    ExpenseHandler linkTo(ExpenseHandler next) {
        this.next = next;
        return next;
    }

    final void handle(Expense e) {
        if (canHandle(e)) {
            process(e);
        } else if (next != null) {
            next.handle(e);
        } else {
            throw new IllegalStateException("nobody can approve " + e);
        }
    }

    abstract boolean canHandle(Expense e);
    abstract void process(Expense e);
}
```

`handle` is `final`, so no subclass can break the passing rule. Each handler only fills in two
small methods: `canHandle` ("is this mine?") and `process` ("what do I do with it?"). A fixed
skeleton in the base class with steps the subclasses fill in is itself a pattern, the
[Template Method](/patterns/template-method-pattern/).

The team lead can handle anything up to 1,000, the manager up to 5,000, the director up to
25,000. Each class is two lines, and knows nothing about the others:

```java
class TeamLead extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 1_000; }
    void process(Expense e) { /* the team lead signs */ }
}

class Manager extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 5_000; }
    void process(Expense e) { /* the manager signs */ }
}

class Director extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 25_000; }
    void process(Expense e) { /* the director signs */ }
}
```

```mermaid {alt="Class diagram: the abstract ExpenseHandler has a private next field pointing to another ExpenseHandler, a linkTo method, a final handle method, and abstract canHandle and process methods; TeamLead, Manager and Director extend it." caption="One base class owns the passing; each handler owns one rule."}
classDiagram
  class ExpenseHandler {
    <<abstract>>
    -ExpenseHandler next
    +linkTo(ExpenseHandler next) ExpenseHandler
    +handle(Expense e) void
    #canHandle(Expense e) boolean*
    #process(Expense e) void*
  }
  class TeamLead
  class Manager
  class Director
  ExpenseHandler --> ExpenseHandler : next
  ExpenseHandler <|-- TeamLead
  ExpenseHandler <|-- Manager
  ExpenseHandler <|-- Director
  note for ExpenseHandler "handle() is final: handle it, or hand it on"
```

Now the **client** builds the chain: a team lead, linked to a manager, linked to a director. Then
it sends the flight to the first link:

```java
ExpenseHandler chain = new TeamLead();
chain.linkTo(new Manager())
     .linkTo(new Director());

chain.handle(new Expense("flight to Lisbon", 3_000));   // the manager signs
```

The team lead says no, and passes it on. The manager says yes, and signs. The director never even
sees it:

```mermaid {alt="Sequence: the client calls handle with the 3,000 expense on TeamLead; TeamLead's canHandle returns false, so it calls handle on Manager; Manager's canHandle returns true and it processes the expense; Director is never called." caption="The request walks the chain until a link says 'mine'."}
sequenceDiagram
  participant C as Client
  participant L as TeamLead
  participant M as Manager
  participant D as Director
  C->>L: handle(flight, 3,000)
  Note over L: canHandle? no (over 1,000)
  L->>M: next.handle(e)
  Note over M: canHandle? yes
  M->>M: process(e): signed
  Note over D: never called
```

| Role | In this example | Responsibility |
|---|---|---|
| **Handler** | `ExpenseHandler` | holds `next`; the fixed "handle it, or hand it on" rule |
| **Concrete handlers** | `TeamLead`, `Manager`, `Director` | one rule each (`canHandle`) and the work (`process`) |
| **Client** | the code that wires and submits | builds the chain, sends to the first link |
| **Request** | `Expense` | the thing that travels |

A variant you'll also see: an **interface** `ExpenseHandler { void handle(Expense e); }` where each
class stores its own `next` and decides itself when to forward. It's more flexible (a handler can
do some work *and* forward), but every class must remember to forward; the abstract base class
makes forgetting impossible.

## Anatomy and design choices

### Reordering and inserting is configuration

Now the new rules from before are easy. The fraud check becomes a handler, and goes first. The
travel desk goes second. The existing handlers don't change at all:

```java
class FraudCheck extends ExpenseHandler {
    boolean canHandle(Expense e) { return looksSuspicious(e); }
    void process(Expense e) { /* send it to the fraud team, and stop */ }
}

class Cfo extends ExpenseHandler {
    boolean canHandle(Expense e) { return true; }   // catches everything that's left
    void process(Expense e) { /* approve or reject, but always answer */ }
}
```

```java
ExpenseHandler chain = new FraudCheck();
chain.linkTo(new TravelDesk())
     .linkTo(new TeamLead())
     .linkTo(new Manager())
     .linkTo(new Director())
     .linkTo(new Cfo());          // the end of the chain always decides
```

The order of the chain is now **configuration**. A different department can build a different
chain from the same pieces, and each rule can be unit-tested on its own:
`new TravelDesk().canHandle(trip)` needs no other handler.

```mermaid {alt="The rewired chain from top to bottom: FraudCheck for suspicious expenses, TravelDesk for trips under 2,000, TeamLead up to 1,000, Manager up to 5,000, Director up to 25,000, and Cfo, which catches everything that's left." caption="The same pieces, a new order, and a last link that always answers."}
flowchart TD
  F["FraudCheck<br/>suspicious?"] -->|next| T["TravelDesk<br/>trips under 2,000"]
  T -->|next| L["TeamLead<br/>up to 1,000"]
  L -->|next| M["Manager<br/>up to 5,000"]
  M -->|next| D["Director<br/>up to 25,000"]
  D -->|next| C["Cfo<br/>everything left"]
  class F c3
  class T c6
  class L c1
  class M c2
  class D c4
  class C c5
```

### The end of the chain: the request nobody handles

Watch the end of the chain. Send 40,000 down the old chain (team lead, manager, director), and it
runs past the director, and **off the end**. Our base class throws. But a careless version would
simply do nothing, and the request would vanish without a trace. That's the classic pitfall: **the
request nobody handles**.

The fix is a **last link that always answers**. Here, the `Cfo` catches everything that's left,
and either approves it or rejects it. But it always answers.

```mermaid {alt="Two chains: without a final link, the 40,000 expense passes TeamLead, Manager and Director and falls off the end, either throwing or silently vanishing; with Cfo at the end, the same expense is always answered." caption="Make sure the end of the chain always answers."}
flowchart LR
  subgraph OLD["Old chain"]
    direction TB
    A1["40,000"] --> L1["TeamLead: no"] --> M1["Manager: no"] --> D1["Director: no"] --> X["off the end:<br/>throws, or vanishes"]
  end
  subgraph NEW["With a last link"]
    direction TB
    A2["40,000"] --> L2["TeamLead: no"] --> M2["Manager: no"] --> D2["Director: no"] --> C2["Cfo: always answers"]
  end
  OLD ~~~ NEW
  class A1,A2 hl
  class X bad
  class C2 good
```

### Stop at the first handler, or work and pass on?

Another design choice: does the request stop at the first handler? In the **classic pattern**, it
does: exactly one link handles it. In the **pipeline variant**, every link does a bit of work and
then passes it on. That's how web middleware works (logging, compression, authentication all run
for the same request).

```mermaid {alt="Classic chain: A passes, B handles and the request stops, C is never reached. Pipeline: A works and passes on, B works and passes on, C works; every link runs." caption="Classic: one handler stops it. Pipeline: every link does a share."}
flowchart LR
  subgraph CLASSIC["Classic: stop at the first"]
    direction TB
    A["A: pass"] --> B["B: handled, stop"] -.-> C["C: never reached"]
  end
  subgraph PIPE["Pipeline: work, then pass on"]
    direction TB
    P["A: works"] --> Q["B: works"] --> R["C: works"]
  end
  CLASSIC ~~~ PIPE
  class B good
  class C muted
  class P,Q,R c6
```

### Debugging long chains

And one warning. You can't see the path in the code any more: the order lives in the wiring, not
in an `if` ladder you can read top to bottom. So **log each hop** (a line like `TeamLead: pass`,
`Manager: handled` in the base class's `handle` costs nothing), and **keep your chains short**.

## A realistic example: servlet filters

You use this pattern every time a Java web app handles a request. Before the request reaches your
servlet, it passes through a **chain of filters**. Here: a timing filter, then an auth filter, then
the reports servlet. A request comes in from someone who isn't logged in. The auth filter stops it
right there and sends back an *unauthorized* error (401). The servlet never runs.

In code, each filter gets the request, and the **filter chain**. If the user isn't logged in, it
sends the error and returns: that's *handling it*. Otherwise, it calls `doFilter` on the chain:
that's *handing it on*.

```java
class AuthFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        if (!isLoggedIn(req)) {
            ((HttpServletResponse) res).sendError(401);   // handled: the chain stops here
            return;
        }
        chain.doFilter(req, res);                         // not mine: hand it on
    }
}
```

A filter can even work on **both sides**. The timing filter notes the start time, lets the rest of
the chain run, and then logs how long it took:

```java
class TimingFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        long start = System.nanoTime();
        chain.doFilter(req, res);                         // the rest of the chain runs here
        log.info("took " + (System.nanoTime() - start) + " ns");
    }
}
```

```mermaid {alt="Sequence: a browser sends GET /reports; TimingFilter notes the start and calls the chain; AuthFilter checks the session. Without a session it answers 401 and ReportServlet never runs. With a session it calls the chain, ReportServlet renders the page, and on the way back TimingFilter logs the time taken." caption="Each filter stops the request or hands it on, and can work before and after the rest."}
sequenceDiagram
  actor B as Browser
  participant T as TimingFilter
  participant A as AuthFilter
  participant S as ReportServlet
  B->>T: GET /reports
  T->>A: chain.doFilter(req, res)
  alt not logged in
    A-->>B: 401 Unauthorized
    Note over S: never runs
  else logged in
    A->>S: chain.doFilter(req, res)
    S-->>T: the report page
    Note over T: log "took 42 ms"
    T-->>B: the report page
  end
```

And the servlet never knows that the filters exist. They're listed in configuration (`web.xml`,
`@WebFilter`, or your framework's registration), and you can add or reorder them without touching
it. **Spring Security** works the same way: its `SecurityFilterChain` is a list of filters, and the
middleware of most web frameworks (and the handler pipelines of HTTP clients) follow the same
shape. Note that filters are the *pipeline* variant: most of them do a little work and hand the
request on, and only some, like the auth filter, stop it.

Other places you'll find a chain: GUI event bubbling (a click goes to the button, then its panel,
then the window, until someone handles it), `java.util.logging` handlers passing records to their
parent loggers, and exception handling itself (the call stack is searched, frame by frame, for a
`catch` that can handle the exception).

## Chain of Responsibility vs Decorator (and Command)

Chain of Responsibility is often confused with the **[Decorator pattern](/patterns/decorator-pattern/)**.
Both wrap another object and forward calls to it, so in code they can look alike. Here are Java's
input streams: a buffered stream, around a zip stream, around a file stream.

```java
InputStream in = new BufferedInputStream(
                     new GZIPInputStream(
                         new FileInputStream("report.gz")));
```

Every `read()` goes all the way through. Each layer adds something (buffering, unzipping), but it
**always forwards**. In a chain, **any link can stop** the request. Usually exactly one of them
handles it, and the rest never see it.

```mermaid {alt="Decorator: read goes from BufferedInputStream to GZIPInputStream to FileInputStream; every layer always forwards and adds behavior. Chain of Responsibility: the expense goes to TeamLead, which hands it on to Manager, which stops it; Director never sees it." caption="A decorator always forwards. A chain may stop."}
flowchart LR
  subgraph DEC["Decorator: always forwards"]
    direction TB
    B1["BufferedInputStream<br/>+ buffering"] -->|"read()"| G1["GZIPInputStream<br/>+ unzipping"]
    G1 -->|"read()"| F1["FileInputStream<br/>reads the bytes"]
  end
  subgraph COR["Chain: any link may stop"]
    direction TB
    L2["TeamLead"] -->|"hand it on"| M2["Manager: stops it"]
    M2 -.-> D2["Director: never sees it"]
  end
  DEC ~~~ COR
  class B1 c6
  class G1 c1
  class F1 c2
  class L2 c1
  class M2 good
  class D2 muted
```

| | **Decorator** | **Chain of Responsibility** |
|---|---|---|
| Does every layer forward? | always | only if it doesn't handle it |
| Does the core object run? | always | maybe nobody handles it |
| Purpose | add behavior around an object | find the object that handles a request |
| Typical count of "doers" | all of them | usually exactly one |

Middleware sits in between: most filters forward like decorators, but some stop the request like
a chain.

And the [Command pattern](/patterns/command-pattern/)? That's a different question. **Command
turns a request into an object. Chain of Responsibility decides who handles it.** They work well
together: a command object can travel down a chain, and the first handler that knows how to run it
does.

> **A decorator always passes it on. A chain decides who stops it.**

## When to use it (and when not to)

**Use it when:**

- ✓ several objects might handle a request, and the sender shouldn't care which,
- ✓ the set of handlers, or their order, changes by configuration (per department, per customer,
  per environment),
- ✓ you want to test each rule on its own.

**Skip it when:**

- ✗ there's always exactly one obvious receiver: just call it,
- ✗ the rules are a simple lookup (one handler per type or code): use a `Map`,
- ✗ a lost request would be dangerous and you can't guarantee a last link that always answers.

And watch out for long chains: they're hard to debug, and every request pays for every hop.

```mermaid {alt="Decision flowchart: if there is always one obvious receiver, just call it; if the receiver is a simple lookup by type, use a map; otherwise use a chain of responsibility, and make sure the chain ends with a handler that always answers." caption="When a chain pays for itself."}
flowchart TD
  Q1{"Always one obvious<br/>receiver?"}
  Q1 -->|yes| K1["Just call it"]
  Q1 -->|no| Q2{"Receiver is a simple<br/>lookup by type?"}
  Q2 -->|yes| K2["Use a Map"]
  Q2 -->|no| Q3{"Several handlers whose set<br/>or order changes?"}
  Q3 -->|no| K3["An if/else is fine"]
  Q3 -->|yes| U["Chain of Responsibility,<br/>ending in a link that always answers"]
  class U good
  class K1,K2,K3 muted
```

## Recap

An `if`/`else` ladder makes the sender know every receiver. Instead, give every handler **one job,
and one neighbor**. Build the chain from outside, and make sure its end always answers.

```mermaid {alt="Recap chain: an if/else ladder where the sender knows everyone is replaced by handlers with one rule and one neighbor each; each one handles the request or hands it on; the chain is built from outside; and its end always answers." caption="Handle it, or hand it on."}
flowchart LR
  A["if/else ladder:<br/>sender knows everyone"] --> B["one rule,<br/>one neighbor"]
  B --> C["handle it,<br/>or hand it on"]
  C --> D["built from outside,<br/>end always answers"]
  class A bad
  class B c2
  class C hl
  class D good
```

- The **sender** knows only the first link; the receivers are decoupled from it.
- Each **handler** knows its own rule and its next handler, and nothing else.
- The **chain** is configuration: add, remove and reorder links without touching anyone.
- Put a **last link that always answers**, and log each hop.
- **A decorator always passes it on. A chain decides who stops it.**

> **Handle it, or hand it on.**

## Complete code

For reference, the whole expense chain, written out so it compiles:

```java
record Expense(String description, int amount, boolean isTravel) {
    Expense(String description, int amount) { this(description, amount, false); }
}

abstract class ExpenseHandler {
    private ExpenseHandler next;

    ExpenseHandler linkTo(ExpenseHandler next) {
        this.next = next;
        return next;
    }

    final void handle(Expense e) {
        if (canHandle(e)) {
            System.out.println(getClass().getSimpleName() + ": handled " + e.description());
            process(e);
        } else if (next != null) {
            System.out.println(getClass().getSimpleName() + ": pass");
            next.handle(e);
        } else {
            throw new IllegalStateException("nobody can approve " + e);
        }
    }

    abstract boolean canHandle(Expense e);
    abstract void process(Expense e);
}

class FraudCheck extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() % 1_000 == 999; }   // a toy rule
    void process(Expense e) { System.out.println("  sent to the fraud team"); }
}

class TravelDesk extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.isTravel() && e.amount() <= 2_000; }
    void process(Expense e) { System.out.println("  booked through the travel desk"); }
}

class TeamLead extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 1_000; }
    void process(Expense e) { System.out.println("  signed by the team lead"); }
}

class Manager extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 5_000; }
    void process(Expense e) { System.out.println("  signed by the manager"); }
}

class Director extends ExpenseHandler {
    boolean canHandle(Expense e) { return e.amount() <= 25_000; }
    void process(Expense e) { System.out.println("  signed by the director"); }
}

class Cfo extends ExpenseHandler {
    boolean canHandle(Expense e) { return true; }
    void process(Expense e) { System.out.println("  decided by the CFO"); }
}

public class Expenses {
    public static void main(String[] args) {
        ExpenseHandler chain = new FraudCheck();
        chain.linkTo(new TravelDesk())
             .linkTo(new TeamLead())
             .linkTo(new Manager())
             .linkTo(new Director())
             .linkTo(new Cfo());

        chain.handle(new Expense("flight to Lisbon", 3_000, true));   // Manager
        chain.handle(new Expense("new office", 40_000));              // Cfo
    }
}
```
