State Pattern
The State pattern: giving each state of an object its own class, so behaviour changes when the state changes, and deciding which class chooses the next state.
A document can be a draft, in review, or published, and "publish" means something different in each: submit it, approve it, or do nothing. Written with a status field, every method opens with the same set of checks, and each new status adds a branch to all of them. The State pattern gives each state its own class, and the object hands every request to whichever state it currently holds.
This topic opens on those repeated checks, then reads the participants off the class diagram and maps a state diagram onto the classes. The template runs two states that hand control to each other, in Python, Java and TypeScript, with a context that never checks which state it holds.
Two examples follow: a document moving from draft to published, and the Gang of Four's own case, a network connection whose open, send and close depend on whether it is listening, established or closed. The gotcha is transitions decided in two places at once, and the exercise builds a vending machine.
By the end you can recognise State, write one with its transitions, and say which class decides each change of state.
Contents
8 cardsnot started