AlgoViz

Chain of responsibility

medium 45 min

A request travels past several handlers until one takes it, or until one stops it.

Watch lesson4:36

Example: expense approval

The same idea without linked objects: a list of data.

The point: when handlers differ only in numbers, they are not classes. They are rows.

Problem

15,000 dollars for a conference

A manager approves up to 1,000, a director up to 10,000, the VP Finance up to 50,000, the CEO without limit. Nobody approves their own expense. Auditors want to see who looked at it and why it went on.

The way of one expense

The CEO never sees it. That is the purpose of the chain, not a detail.

Approval chain

in orderApprovalChain- approvers: List<Approver>+ decide(e): DecisionApprover+ role: String+ person: String+ limit: int or none+ verdict(e): String

1/3A list in order

The chain is a list. An approver does not know the next one.

has (lives on)depends onuses

One class with a limit instead of four classes that differ in a number.

Build the approval chain

What goes in and what comes out.

from dataclasses import dataclass@dataclass(frozen=True)class Expense:    who: str    amount: int          # whole dollars    reason: str@dataclass(frozen=True)class Decision:    approved_by: str    trail: tuple

Lines 4 to 8

Whole dollars. Money in floats would one day put 1,000 above 1,000.

1 of 2

Linked objects or a list?

Linked handlersList and runner
Handler knowsthe next onenothing
Same handler in two chainsno, it has one nextyes
Trail, timing, limitsin the base classin the loop
Work after the restnaturalneeds composed functions
Change while runningdangerousswap the whole list