State Pattern
Give each mode of an object its own class, so the object changes behavior by swapping the state object instead of branching on a flag.
Overview
The problem: behavior that depends on a mode
Some objects behave differently depending on what mode they are in. A vending machine ignores a button press until money is inserted. A document cannot be published while it is still a draft. A media player treats the play button as pause while it is playing.
The first version of such code keeps a mode field and checks it inside every method. Each new event adds a branch to every method, and each new mode adds a branch to every event. The table below is the whole behavior of a small vending machine. Every cell is one branch somewhere in the code.
- Idle — go to Has money — nothing happens — nothing happens
- Has money — stay, add to credit — dispense, go to Dispensing — nothing happens
- Dispensing — refused — refused — go to Idle
Three modes and three events give nine cells. Six modes and six events give thirty-six. Spread across methods as if and elif, that many branches is where bugs hide.
Interview questions
- Show the smell the State pattern fixes, and the fix.
- Who should own the transitions, the states or the context?
- Can state objects be shared between contexts?
- How do you test a class built with the State pattern?
- Where do entry and exit actions go?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio