Design Patterns
State
Switching state takes O(1) time (a constant amount). You're just swapping which small state object is 'current'.
The idea, in plain English
The state pattern works like a traffic light. Each color simply knows what comes next — red knows green comes after it, and so on. The light just asks 'what's next?' and switches automatically. In code, an object's behavior changes on its own, based on what 'state' it's currently in.
How it works
- 1You give each state — Red, Green, Yellow — its own small object. Each one only knows what state comes after it.
- 2The main object just holds 'whichever state I'm currently in', and asks that state to move things along.
- 3When a state object switches to the next state, the main object's behavior changes too, automatically. You need no giant if/else.
When you'd use it
Use this when an object behaves differently depending on its current mode or phase. Examples: a traffic light, an order status (placed, shipped, delivered), or a media player (playing, paused, stopped).
Common beginner mistakes
- Don't cram all the state-transition logic into one giant if/else. Let each state own its own transition.
- Always update the current state, or the object gets stuck repeating the same behavior forever.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Start: Red
Change: Green
Change: Yellow
Change: RedNot sure this is the right topic? See the learning paths → or where this leads →