# State PatternOne 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.

{{< lesson-video youtube="77obGfUSQnA" title="The State Pattern" >}}

## One button, three behaviors

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.

```mermaid {alt="Pressing the same button leads to three outcomes depending on the machine's state: no coin shows Insert coin, has coin dispenses a snack, sold out refunds the coin."}
flowchart TD
  P(["pressButton()"]) --> Q{"What situation<br/>is the machine in?"}
  Q -->|no coin| A["Show 'Insert coin'"]
  Q -->|has coin| B["Dispense a snack"]
  Q -->|sold out| C["Refund the coin"]
  class A nocoin
  class B hascoin
  class C soldout
```

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*.

## A simpler machine: the traffic light

Before touching any code, study an even simpler machine. A traffic light is green, then
yellow, then red, and back to green again. Forever.

```mermaid {alt="Traffic light state diagram: Green to Yellow to Red to Green, every transition triggered by the same timer event." caption="Every arrow carries the same event (the timer), yet each state reacts differently."}
stateDiagram-v2
  direction LR
  [*] --> Green
  Green --> Yellow: timer
  Yellow --> Red: timer
  Red --> Green: timer
  class Green good
  class Yellow warn
  class Red bad
```

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**):

```mermaid {alt="Vending machine state diagram: NoCoin goes to HasCoin on insertCoin; HasCoin goes back to NoCoin on pressButton, or to SoldOut when stock reaches zero; SoldOut goes to NoCoin on refill."}
stateDiagram-v2
  [*] --> NoCoin
  NoCoin --> HasCoin: insertCoin()
  HasCoin --> NoCoin: pressButton()
  HasCoin --> SoldOut: pressButton() [stock = 0]
  SoldOut --> NoCoin: refill()
  class NoCoin nocoin
  class HasCoin hascoin
  class SoldOut soldout
```

## The obvious way: a switch in every method

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:

```java
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:

```mermaid {alt="A single change request, adding maintenance mode and cancel, forces edits in every method: a new constant, a new case in pressButton, insertCoin and refill, and a whole new cancel method."}
flowchart LR
  R["New requirement:<br/>MAINTENANCE mode + cancel()"]
  R --> E0["+ constant MAINTENANCE"]
  R --> E1["pressButton(): + case"]
  R --> E2["insertCoin(): + case"]
  R --> E3["refill(): + case"]
  R --> E4["+ cancel(): a case for every state"]
  class R warn
  class E0,E1,E2,E3,E4 bad
```

Here's the result:

```java
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:

1. **Scattered:** the logic for any one state (say, *has coin*) is spread across every method.
2. **Fragile:** every switch must stay complete. Forget a single case, and you get a silent bug.
3. **Hidden transitions:** the moments the machine changes state (`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?

## The key insight: the hidden behavior table

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 += n
- `HasCoinState`: insertCoin → "Already paid" · pressButton → dispense, go to the next state · refill → stock += n
- `SoldOutState`: insertCoin → refund · pressButton → refund · refill → stock += n, go to NoCoin

Now watch what happens when we add maintenance mode in each design:

```mermaid {alt="Side-by-side comparison. Sliced by event: adding Maintenance edits all three methods. Sliced by state: the three existing state classes are untouched and one new MaintenanceState class is added." caption="Same table, cut two ways. Red = edited, gray = untouched, green = new."}
flowchart LR
  subgraph ROWS["Sliced by event (switch)"]
    direction TB
    m1["insertCoin()<br/>+ case MAINTENANCE"]
    m2["pressButton()<br/>+ case MAINTENANCE"]
    m3["refill()<br/>+ case MAINTENANCE"]
  end
  subgraph COLS["Sliced by state (State pattern)"]
    direction TB
    c1["NoCoinState"]
    c2["HasCoinState"]
    c3["SoldOutState"]
    c4["+ MaintenanceState"]
  end
  ROWS ~~~ COLS
  class m1,m2,m3 bad
  class c1,c2,c3 muted
  class c4 good
```

Same information. Same table. We just cut it the other way.

> **Group your code by state, not by event.**

## Building the pattern: the cartridge slot

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:

```mermaid {alt="The vending machine (the console) has one state slot holding the current cartridge, NoCoinState. HasCoinState and SoldOutState are spare cartridges that can be swapped in."}
flowchart LR
  VM["VendingMachine<br/>(the console)"] -->|"state slot"| CUR["NoCoinState<br/>(plugged in)"]
  CUR -.->|"swap"| H["HasCoinState"]
  CUR -.->|"swap"| S["SoldOutState"]
  class CUR nocoin
  class H hascoin
  class S soldout
```

Here's the structure we're about to write:

```mermaid {alt="Class diagram: VendingMachine holds a State. State is an interface with insertCoin, pressButton and refill. NoCoinState, HasCoinState and SoldOutState implement it."}
classDiagram
  direction TB
  class VendingMachine {
    -State state
    +int stock
    +setState(State s)
    +insertCoin()
    +pressButton()
    +refill(int n)
  }
  class State {
    <<interface>>
    +insertCoin(VendingMachine m)
    +pressButton(VendingMachine m)
    +refill(VendingMachine m, int n)
  }
  VendingMachine o--> State : current state
  State <|.. NoCoinState
  State <|.. HasCoinState
  State <|.. SoldOutState
```

**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:

```java
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:

```java
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**:

```java
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;
    }
}
```

### Running it

Follow the calls as a customer uses the machine. The machine always forwards the call;
*which* cartridge answers changes as the state changes:

```mermaid {alt="Sequence diagram: the customer presses the button and NoCoinState asks for a coin; the customer inserts a coin and NoCoinState swaps in HasCoinState; the customer presses again and HasCoinState dispenses, lowers the stock and swaps in NoCoinState."}
sequenceDiagram
  actor C as Customer
  participant M as VendingMachine
  participant N as NoCoinState
  participant H as HasCoinState
  C->>M: pressButton()
  M->>N: pressButton(m)
  N-->>M: show("Insert coin")
  C->>M: insertCoin()
  M->>N: insertCoin(m)
  N->>M: setState(new HasCoinState())
  Note over M,H: same machine, new cartridge
  C->>M: pressButton()
  M->>H: pressButton(m)
  H->>M: dispense(), stock--
  H->>M: setState(new NoCoinState())
```

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.

## The anatomy of the pattern

Zoomed out, the pieces have official names:

```mermaid {alt="Generic State pattern class diagram: Context holds a State and delegates request() to state.handle(); State is an interface with handle(ctx); ConcreteStateA, B and C implement it."}
classDiagram
  direction TB
  class Context {
    -State state
    +setState(State s)
    +request()
  }
  class State {
    <<interface>>
    +handle(Context ctx)
  }
  Context o--> State : delegates to
  State <|.. ConcreteStateA
  State <|.. ConcreteStateB
  State <|.. ConcreteStateC
  note for Context "request() calls state.handle(this)"
```

| 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.

### Choice 1: who decides the transitions?

**The states decide** (our version), e.g. `m.setState(new SoldOutState());` inside a
state. ✓ Flexible. ✗ States know about each other:

```mermaid {alt="States decide: NoCoinState, HasCoinState and SoldOutState each point directly to the next state they set."}
flowchart LR
  N["NoCoinState"] -->|setState| H["HasCoinState"]
  H -->|setState| N
  H -->|setState| S["SoldOutState"]
  S -->|setState| N
  class N nocoin
  class H hascoin
  class S soldout
```

**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 |

```mermaid {alt="Context decides: the context's transition table picks the next state; the three state classes don't reference each other."}
flowchart TD
  T["Context<br/>transition table"] --> N["NoCoinState"]
  T --> H["HasCoinState"]
  T --> S["SoldOutState"]
  class T hl
  class N nocoin
  class H hascoin
  class S soldout
```

**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.

### Choice 2: a brand-new object on every transition?

If a state has no fields of its own, no. It can be a **single shared instance**, created
once and reused forever:

```java
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);
```

```mermaid {alt="Many transitions that each created a new NoCoinState now all point to one shared instance, States.NO_COIN."}
flowchart LR
  t1["transition 1"] --> X["States.NO_COIN<br/>(one shared instance)"]
  t2["transition 2"] --> X
  t3["transition 3"] --> X
  class X nocoin
```

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.

## Example 2: a publishing workflow

Vending machines are cute. Here's what this looks like at work: a publishing system where
documents move from **draft**, to **moderation**, to **published**.

```mermaid {alt="Document workflow: Draft goes to Moderation on publish; Moderation goes to Published on publish by an admin, or back to Draft on reject."}
stateDiagram-v2
  direction LR
  [*] --> Draft
  Draft --> Moderation: publish()
  Moderation --> Published: publish() [admin]
  Moderation --> Draft: reject()
  class Draft muted
  class Moderation amber
  class Published good
```

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:

```java
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:

```mermaid {alt="The same workflow with one addition: Published goes to a new Archived state on expire. Everything else is unchanged." caption="One new state, one new arrow. Everything else is untouched."}
stateDiagram-v2
  [*] --> Draft
  Draft --> Moderation: publish()
  Moderation --> Published: publish() [admin]
  Moderation --> Draft: reject()
  Published --> Archived: expire() after 30 days
  class Draft,Moderation,Published muted
  class Archived maint
```

```java
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 |

## State vs Strategy

If you know the [Strategy pattern](/patterns/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*:

```mermaid {alt="Strategy: the client chooses AvoidTolls once and the navigator keeps using it. State: the vending machine's current state replaces itself, from NoCoinState to HasCoinState to SoldOutState, as events happen."}
flowchart LR
  subgraph STRAT["Strategy: chosen from outside"]
    direction TB
    CL["Client"] -->|"chooses once"| NAV["Navigator"]
    NAV -->|"uses"| AT["AvoidTolls"]
  end
  subgraph STATE["State: changes itself"]
    direction TB
    S1["NoCoinState"] -->|"setState()"| S2["HasCoinState"]
    S2 -->|"setState()"| S3["SoldOutState"]
  end
  class AT nocoin
  class S1 nocoin
  class S2 hascoin
  class S3 soldout
```

| | **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.**

## When to use it (and when not to)

```mermaid {alt="Decision flowchart: if behavior barely depends on state, a boolean or enum is enough. If it does, and the same switch on state repeats across methods or new states keep arriving, use the State pattern; otherwise keep it simple."}
flowchart TD
  Q1{"Does behavior change a lot<br/>depending on state?"}
  Q1 -->|no| K1["Keep it simple:<br/>a boolean or an enum"]
  Q1 -->|yes| Q2{"Same switch(state) in many methods,<br/>or new states keep arriving?"}
  Q2 -->|yes| U["Use the State pattern"]
  Q2 -->|"no: two states, tiny logic"| K2["A class per state is overkill"]
  class U good
  class K1,K2 muted
```

**Use the State pattern when:**

- ✓ an object's behavior changes a lot depending on its state,
- ✓ you see the same `switch (state)` repeated across many methods,
- ✓ you expect new states to keep arriving.

**Skip it when:**

- ✗ you only have two states and a boolean: a class per state is overkill,
- ✗ the logic is tiny,
- ✗ the states are mostly data with little behavior: a simple `enum` may be all you need.

## Recap

```mermaid {alt="Recap chain: every stateful object hides a behavior table; slice it by state; each column becomes a class; each class is a cartridge; the object runs whichever one is plugged in."}
flowchart LR
  A["Behavior<br/>table"] --> B["Slice<br/>by state"]
  B --> D["One class per column<br/>(a cartridge)"]
  D --> E["Object runs the<br/>plugged-in one"]
  class E good
```

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.**

## Complete code

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.)

```java
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.
