November 24, 202612 minutes
One object, one button, different behavior. Learn how the State pattern groups code by state instead of by event, with diagrams, Java examples, and a narrated video.
A vending machine has exactly one button. Press it and you might get a snack, a polite “insert coin” message, or your money back. Same machine, same button, three completely different behaviors. So how would you actually write the code for this? The answer is surprisingly elegant, and it has a name: the State pattern.
Prefer to watch? The narrated video covers the same lesson (about 10 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.
Walk up to the machine and press the button. Nothing happens; the screen just says INSERT COIN. Fair enough. Drop in a coin and press the very same button: this time a snack drops into the tray. Now imagine the machine is sold out. You insert a coin, press that same button again, and the machine hands your money right back.
One object, one input, three behaviors. Whatever we write has to make a single method behave like three different methods, depending on what situation the object is in.
Before touching any code, study an even simpler machine. A traffic light is green, then yellow, then red, and back to green again. Forever.
Each box is a state the light can be in, and the arrows show how it moves from one to the next. Notice something: every arrow is labeled with the same thing, the timer. The light only ever receives one kind of event, but what it does in response depends entirely on which state it’s in right now. That gives us three words for the rest of this lesson:
| Term | Meaning | In code |
|---|---|---|
| State | the situation an object is in right now | a value, or (soon) an object |
| Event | something that happens to it | a method call |
| Transition | moving from one state to another in response to an event | changing the current state |
Our vending machine works exactly the same way. It has three states (no coin, has coin, sold out) and three events (insert coin, press button, refill):
Here’s how most of us would write it the first time. Store the state as a number, and make every method switch on it:
class VendingMachine {
static final int NO_COIN = 0, HAS_COIN = 1, SOLD_OUT = 2;
int state = NO_COIN, stock = 5;
void pressButton() {
switch (state) {
case NO_COIN -> show("Insert coin");
case HAS_COIN -> {
dispense(); stock--;
state = (stock == 0) ? SOLD_OUT : NO_COIN;
}
case SOLD_OUT -> refund();
}
}
void insertCoin() {
switch (state) {
case NO_COIN -> state = HAS_COIN;
case HAS_COIN -> show("Already paid");
case SOLD_OUT -> refund();
}
}
void refill(int n) {
switch (state) {
case NO_COIN, HAS_COIN -> stock += n;
case SOLD_OUT -> { stock += n; state = NO_COIN; }
}
}
}Look at pressButton(): with no coin, ask for one. With a coin, dispense a snack, lower
the stock, and pick the next state. When sold out, refund the money. insertCoin() and
refill() each have their own switch too.
And honestly? For now, this is fine. It works. It’s readable. Then the product manager shows up.
New requirement: a maintenance mode. While a technician is working, every button should say “Out of service”. Also: add a
cancel()button.
So we add a constant. Then a new case in pressButton(). Another in insertCoin().
Another in refill(). And cancel() is a whole new method with a case for every single
state. One requirement ripples through the entire class:
Here’s the result:
class VendingMachine {
static final int NO_COIN = 0, HAS_COIN = 1, SOLD_OUT = 2;
static final int MAINTENANCE = 3;
int state = NO_COIN, stock = 5;
void pressButton() {
switch (state) {
case NO_COIN -> show("Insert coin");
case HAS_COIN -> {
dispense(); stock--;
state = (stock == 0) ? SOLD_OUT : NO_COIN;
}
case SOLD_OUT -> refund();
case MAINTENANCE -> show("Out of service");
}
}
void insertCoin() {
switch (state) {
case NO_COIN -> state = HAS_COIN;
case HAS_COIN -> show("Already paid");
case SOLD_OUT -> refund();
case MAINTENANCE -> refund();
}
}
void refill(int n) {
switch (state) {
case NO_COIN, HAS_COIN -> stock += n;
case SOLD_OUT -> { stock += n; state = NO_COIN; }
case MAINTENANCE -> show("Out of service");
}
}
void cancel() {
switch (state) {
case HAS_COIN -> { refund(); state = NO_COIN; }
case NO_COIN, SOLD_OUT, MAINTENANCE -> {}
}
}
}Step back and look at what’s happening:
state = …) are buried
deep inside the branches, where they’re hard to see.The problem isn’t the switch statement itself. It’s how the code is organized. So what
if we organized it the other way around?
Every object with states secretly contains a table like this: events down the side, states across the top, and each cell saying what to do when that event happens in that state.
| NoCoin | HasCoin | SoldOut | |
|---|---|---|---|
insertCoin() | accept coin → HasCoin | “Already paid” | refund |
pressButton() | “Insert coin” | dispense → NoCoin / SoldOut | refund |
refill() | stock += n | stock += n | stock += n → NoCoin |
Our switch-based code slices this table into rows. Each method is one row, and the
switch walks across the columns. Every row is a rainbow: every single method mixes
together the logic of every single state.
But we could slice the very same table the other way, into columns. Then each slice holds everything about one state and nothing else, and each column becomes a class:
NoCoinState: insertCoin → accept, go to HasCoin · pressButton → “Insert coin” · refill → stock += nHasCoinState: insertCoin → “Already paid” · pressButton → dispense, go to the next state · refill → stock += nSoldOutState: insertCoin → refund · pressButton → refund · refill → stock += n, go to NoCoinNow watch what happens when we add maintenance mode in each design:
Same information. Same table. We just cut it the other way.
Group your code by state, not by event.
To turn those columns into real code, think of an old game console. The console itself doesn’t know how to play any particular game; it just runs whatever cartridge is plugged in. Same console, different cartridge, different behavior.
Our vending machine becomes the console, each state becomes a cartridge, and the machine has one slot that holds the current state:
Here’s the structure we’re about to write:
1. The slot’s shape: an interface. Every cartridge has to fit the slot, so a state must know how to handle every event. Each method receives the machine, so the state can work with it:
interface State {
void insertCoin(VendingMachine m);
void pressButton(VendingMachine m);
void refill(VendingMachine m, int n);
}2. The console: a context that just delegates. The machine itself shrinks to almost nothing. It holds a reference to the current state, and every method is a single line that forwards the call. No ifs. No switches. It just delegates:
class VendingMachine {
private State state = new NoCoinState();
int stock = 5;
void setState(State s) { this.state = s; }
void insertCoin() { state.insertCoin(this); }
void pressButton() { state.pressButton(this); }
void refill(int n) { state.refill(this, n); }
}3. A cartridge: one concrete state. Here’s the has coin state. Pressing the button dispenses a snack and lowers the stock, and then (this is the important part) the state itself tells the machine which state comes next:
class HasCoinState implements State {
public void insertCoin(VendingMachine m) {
m.show("Already paid");
}
public void pressButton(VendingMachine m) {
m.dispense();
m.stock--;
m.setState(m.stock == 0 ? new SoldOutState()
: new NoCoinState());
}
public void refill(VendingMachine m, int n) {
m.stock += n;
}
}Follow the calls as a customer uses the machine. The machine always forwards the call; which cartridge answers changes as the state changes:
Keep selling, and when the stock hits zero, HasCoinState calls
m.setState(new SoldOutState()) and the sold-out cartridge slides in.
The original definition from the Gang of Four book says it perfectly:
“Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.” — Gamma, Helm, Johnson & Vlissides, Design Patterns (1994)
That’s exactly what happened above. The machine never changed. Its cartridge did.
Zoomed out, the pieces have official names:
| Role | In our example | Responsibility |
|---|---|---|
| Context | VendingMachine | what clients talk to; holds the current state and delegates to it |
| State (interface) | State | the contract every state agrees on |
| ConcreteState | NoCoinState, HasCoinState, SoldOutState | one state’s behavior, plus the transitions leading out of it |
There are two design choices worth knowing.
The states decide (our version), e.g. m.setState(new SoldOutState()); inside a
state. ✓ Flexible. ✗ States know about each other:
The context decides, using something like a transition table. ✓ States stay independent. ✓ All the rules live in one place:
| (state, event) | → next state |
|---|---|
| (NoCoin, insertCoin) | HasCoin |
| (HasCoin, pressButton) | NoCoin |
| (SoldOut, refill) | NoCoin |
Neither is wrong. Pick based on how complex your transition rules are: simple, local rules read well inside the states; many or frequently changing rules are easier to manage in one table.
If a state has no fields of its own, no. It can be a single shared instance, created once and reused forever:
final class States {
static final State NO_COIN = new NoCoinState();
static final State HAS_COIN = new HasCoinState();
static final State SOLD_OUT = new SoldOutState();
}
// inside a state:
m.setState(States.HAS_COIN);This only works when states hold no per-object data. If a state needs its own fields (a timer, a retry count), create a fresh instance per context.
Vending machines are cute. Here’s what this looks like at work: a publishing system where documents move from draft, to moderation, to published.
The same publish() method means different things:
| State | publish() by Author | publish() by Admin |
|---|---|---|
| Draft | → Moderation | → Published |
| Moderation | “Waiting for review” | → Published |
| Published | no-op | no-op |
Here’s the moderation state:
class ModerationState implements DocState {
public void publish(Document d, User u) {
if (u.isAdmin()) d.setState(new PublishedState());
else d.notifyAuthor("Waiting for review");
}
public void reject(Document d) {
d.setState(new DraftState());
}
}Notice that it still has an if statement, on the user’s role. That’s fine. The
State pattern removes branching on the object’s own state, not every conditional in
your program.
Now a new requirement arrives: published documents expire after thirty days and become
archived. We add one new class (ArchivedState), one new arrow, and change a single
place in the published state:
class PublishedState implements DocState {
public void publish(Document d, User u) { } // no-op
public void expire(Document d) {
d.setState(new ArchivedState());
}
}That’s the behavior-table insight paying off: the new state is a new column, not a new case in every method.
Once you see this shape, you’ll find it everywhere:
| System | States |
|---|---|
| TCP connection | Listen → Established → Closed |
| Order | Placed → Paid → Shipped |
| Game character | Idle → Running → Jumping |
| Traffic light | Green → Yellow → Red |
If you know the Strategy pattern, you might be thinking: wait, isn’t this the same thing? Structurally, yes: both have a context holding a reference to an interface with several implementations, and the class diagrams are identical. The intent is completely different, and the difference is who changes the behavior:
| State | Strategy | |
|---|---|---|
| Who picks it? | the object itself, as things happen | the client, from outside |
| Do the implementations know each other? | often (they trigger transitions) | no, they’re independent |
| Changes over time? | constantly | usually set once |
| The question it answers | What situation am I in? | How should I do this task? |
Think of a GPS: you choose “avoid tolls”, and it stays that way. That’s a strategy. A traffic light changes on its own, and you never get a say. That’s state.
Strategy is chosen. State is lived.
Use the State pattern when:
switch (state) repeated across many methods,Skip it when:
enum may be all you need.Every stateful object hides a behavior table. Slice it by state, and each column becomes a class. Each class becomes a cartridge. And the object just runs whichever one is plugged in. One object, one button: whichever state is plugged in decides what happens.
Group your code by state, not by event.
For reference, here’s the full vending machine with all three states, using the same
classes as above. (show, dispense and refund are the machine’s hardware helpers.)
interface State {
void insertCoin(VendingMachine m);
void pressButton(VendingMachine m);
void refill(VendingMachine m, int n);
}
class VendingMachine {
private State state = new NoCoinState();
int stock = 5;
void setState(State s) { this.state = s; }
void insertCoin() { state.insertCoin(this); }
void pressButton() { state.pressButton(this); }
void refill(int n) { state.refill(this, n); }
void show(String message) { System.out.println(message); }
void dispense() { System.out.println("Snack dispensed"); }
void refund() { System.out.println("Coin returned"); }
}
class NoCoinState implements State {
public void insertCoin(VendingMachine m) {
m.setState(new HasCoinState());
}
public void pressButton(VendingMachine m) {
m.show("Insert coin");
}
public void refill(VendingMachine m, int n) {
m.stock += n;
}
}
class HasCoinState implements State {
public void insertCoin(VendingMachine m) {
m.show("Already paid");
}
public void pressButton(VendingMachine m) {
m.dispense();
m.stock--;
m.setState(m.stock == 0 ? new SoldOutState()
: new NoCoinState());
}
public void refill(VendingMachine m, int n) {
m.stock += n;
}
}
class SoldOutState implements State {
public void insertCoin(VendingMachine m) {
m.refund();
}
public void pressButton(VendingMachine m) {
m.refund();
}
public void refill(VendingMachine m, int n) {
m.stock += n;
m.setState(new NoCoinState());
}
}Adding maintenance mode is now one new class, MaintenanceState, plus whatever event
moves the machine into it. None of the existing states change.