CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 3 of 6 · 2 min read

An approval chain

Handlers with a successor.

An expense request needs approval. A team lead can approve up to 5000, a manager up to 20000, a director up to 100000 (made up limits). Above that, nobody can.

abstract class Approver {
    private Approver next;

    Approver then(Approver n) { next = n; return n; }

    final String handle(long amount) {
        if (canApprove(amount)) return name() + " approved " + amount;
        if (next == null) return "nobody approved " + amount;
        return next.handle(amount);
    }

    abstract boolean canApprove(long amount);
    abstract String name();
}

class Limit extends Approver {
    private final String n; private final long max;
    Limit(String n, long max) { this.n = n; this.max = max; }
    boolean canApprove(long a) { return a <= max; }
    String name() { return n; }
}

The client builds the chain once.

Approver lead = new Limit("lead", 5000);
lead.then(new Limit("manager", 20000)).then(new Limit("director", 100000));

A request for 3000 is approved by the lead. A request for 12000 passes the lead, since 12000 is above 5000, and the manager approves it. A request for 90000 reaches the director. A request for 250000 falls off the end, and the answer is "nobody approved 250000".

The pieces match GoF's list. The Handler defines the interface for handling requests and holds a link to its successor (Approver). A ConcreteHandler handles requests it is responsible for and otherwise passes them on (Limit). The Client sends the request to the first handler.

GoF lists the benefits. Coupling falls: a sender need not know who will handle the request, and each handler holds a single reference, to its successor, instead of one to every candidate. Responsibilities also become flexible, because changing the chain at run time adds or alters handlers. A new level, such as a vice president between manager and director, is a new object placed in the line, and the others do not change.

Check yourself: 1. Who approves 12000, and why not the lead? 2. How many references does each handler keep? 3. How would you add a vice president?