State pattern
medium 55 minThe State pattern lets an object change its behaviour when its internal state changes.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: who holds which state, and who answers the same call.
Operations
Vending machine
Buy a cola for 150 with 200 and 100. The arrow from the machine is its current state.
Step 1 of 10
Ready
Display: INSERT COIN
The machine holds noCoin. Display: INSERT COIN.
Step 1: Ready
class VendingMachine: def select_product(self, code): self._state.select_product(self, code)class NoCoin: def insert_coin(self, m, cents): m.balance = cents m.go(m.has_coin, "SELECT PRODUCT") def select_product(self, m, code): m.display = "INSERT COIN FIRST"class HasCoin: def insert_coin(self, m, cents): m.balance += cents def select_product(self, m, code): if m.balance >= m.slots[code].price: m.chosen = code m.go(m.sold, "DISPENSING")class Sold: def insert_coin(self, m, cents): m.give_back(cents) def dispense(self, m): m.give_back(m.balance - m.slots[m.chosen].price) m.balance, m.chosen = 0, None m.go(m.no_coin, "INSERT COIN")- Watch
- The state arrow
- Result
- Same call, other answer
Follow the arrow from the machine. It moves three times.
In the real world
The same state pattern doing real jobs. Pick one and step through it.
The answer of the first call was lost, so the shop calls again.
Step 1 of 5
Accepted
| Id | Event | State | Answer | |
|---|---|---|---|---|
| 1 | e1 | pay | New to Paid | Paid |
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
Event e1, pay. The order moves from New to Paid, and the answer is stored with the id.
Step 1: Accepted
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Taking the money before delegating
criticalIn Sold the coin is refused, but it is already in the balance.
Wrongdef insert_coin(self, cents): self.balance += cents self._state.insert_coin(self)Rightdef insert_coin(self, cents): self._state.insert_coin(self, cents)A public setter for the state
criticalAnyone can jump to Sold without paying, and hooks and log are skipped.
Wrongmachine.state = machine.soldRightdef go(self, state): # tools for states only log(self._state, state) self._state = stateConditions about the state in the context
majorThe question you removed is back.
Wrongdef cancel(self): if self._state is self.has_coin: self.give_back(self.balance)Rightdef cancel(self): self._state.cancel(self)Data in a shared state object
criticalAll documents share the object, so they share the reviewer.
Wrongclass Review: def __init__(self): self.reviewer = NoneRightclass Document: def __init__(self): self.reviewer = NoneWaiting inside a transition
majorNobody can press anything for ten seconds, and a lock is held.
Wrongdef dispense(self, m): sleep(10) m.go(m.no_coin)Rightdef enter(self, m): m.motor.start() # the sensor sends dispenseForgetting a cell silently
majorAn empty inherited method swallows the event.
Wrongclass MachineState: def insert_coin(self, m, cents): passRightclass MachineState(ABC): @abstractmethod def insert_coin(self, m, cents): ...
Interview tips
Draw first
- Events are verbs.
- States are adjectives.
- Fill every cell.
Keep the context boring
- One line per event.
- Data that outlives states.
- One writer of the state.
Refuse completely
- Return the coin.
- Say why.
- Stay in the state.
Know the neighbours
- Strategy is chosen.
- State moves on.
- A table is smaller.
In production
- One event at a time.
- Name, data, version.
- Ids for events.