☰ All patterns
State
Let an object change its behaviour when its internal state changes.
01
Explain it like I'm new
Real-life analogy
A traffic light
The same light behaves differently depending on its colour: red means walk, green means wait. Each colour knows which colour comes next.
😩 The problem
Every method has a switch l.status { case red...; case green... }. Adding a state means editing every switch, and invalid transitions slip through.
💡 The pattern
Make each state its own type implementing a State interface. The context delegates to its current state, and states decide the next state themselves.
02
Play with it
An interactive model of the pattern. Click around, nothing can break.
current state
Red{}
state.CanCross()
true 🚶
💡 Notice there's no switch anywhere. Each state type knows its own behaviour and which state comes next.
03
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
04
When should I use it?
✅ Reach for it when…
- •Workflows: orders, payments, connections, game characters, UI modes.
🚫 Skip it when…
- •Only 2 states with trivial logic. A boolean or small switch is fine.
🐹 Go tip
For simple machines, a map[State][]State of allowed transitions plus a switch is also very idiomatic Go.
🌍 You've already seen it in
TCP connection states, the text/template lexer (states as functions) and order workflows in e-commerce backends.
05
Quick check
One question. No pressure.
In the State pattern, who decides what the next state is?