bigonotes
CS ConceptsDesign Patterns

State Pattern

Model state machines like vending machines and document workflows with one class per state instead of if/else on a state field.

7 min readLast updated

A music player behaves differently when it's stopped, playing, paused, and when its playlist has run out. If you track that with a state string, every method grows an if/elif over every state. State turns each state into its own class; the player delegates to whichever state object is current, and the states decide when to switch. Many LLD interview problems (vending machine, elevator, order lifecycle, ATM) test whether you know this pattern.

Intent#

The original definition puts the effect in one line:

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. (GoF)

Analogy: water. Ice, liquid and steam are the same substance with completely different behavior, depending on state.

The problem: if/elif spaghetti#

Here is the player with a plain state string:

class BadAudioPlayer:
    def __init__(self):
        self.state = "STOPPED"  # STOPPED, PLAYING, PAUSED

    def play(self):
        if self.state == "STOPPED":
            print("Starting playlist.")
            self.state = "PLAYING"
        elif self.state == "PLAYING":
            print("Already playing.")
        elif self.state == "PAUSED":
            print("Resuming.")
            self.state = "PLAYING"

    def pause(self):
        if self.state == "STOPPED":
            print("Nothing is playing.")
        elif self.state == "PLAYING":
            print("Paused.")
            self.state = "PAUSED"
        elif self.state == "PAUSED":
            print("Already paused.")

    def track_finished(self):
        if self.state == "PLAYING":
            print("Next track.")
        else:
            print("No track is playing.")

Three states and three methods already make nine branches to think about. Two problems follow:

  • Unmaintainable: every method (play, pause, skip, ...) needs a branch for every state.
  • Violates Open/Closed: adding PLAYLIST_ENDED means editing every method, which is exactly where bugs creep in.

Structure#

The pattern has three participants.

Participant Role
Context The object clients use (AudioPlayer); holds the current state and delegates every call to it
State interface One method per action the context supports
Concrete states Implement behavior for one state and trigger transitions (context.set_state(...))

A single call flows like this:

  1. The client calls player.pause().
  2. The player calls current_state.pause(player), passing itself.
  3. The state does the work, then calls player.set_state(PausedState()).

The context passes itself to the state so the state can call set_state() and read context data. This two-way link is the part that feels odd at first.

Example 1: music player#

Here's the same player rewritten with the pattern, plus a "playlist ended" state the old version didn't have. Each state is a class, and the player forwards every action.

from abc import ABC, abstractmethod


class PlayerState(ABC):
    @abstractmethod
    def play(self, player: "AudioPlayer") -> None: ...

    @abstractmethod
    def pause(self, player: "AudioPlayer") -> None: ...

    @abstractmethod
    def track_finished(self, player: "AudioPlayer") -> None: ...


class StoppedState(PlayerState):
    def play(self, player):
        print("Starting playlist.")
        player.set_state(PlayingState())  # transition

    def pause(self, player):
        print("Nothing is playing.")

    def track_finished(self, player):
        print("Nothing is playing.")


class PlayingState(PlayerState):
    def play(self, player):
        print("Already playing.")

    def pause(self, player):
        print("Paused.")
        player.set_state(PausedState())

    def track_finished(self, player):
        player.tracks_left -= 1
        if player.tracks_left > 0:
            print(f"Next track. {player.tracks_left} left.")
        else:
            print("Playlist ended.")
            player.set_state(EndedState())


class PausedState(PlayerState):
    def play(self, player):
        print("Resuming.")
        player.set_state(PlayingState())

    def pause(self, player):
        print("Already paused.")

    def track_finished(self, player):
        print("Paused, so no track can finish.")


class EndedState(PlayerState):
    def play(self, player):
        print("Playlist ended. Add tracks to play again.")

    def pause(self, player):
        print("Nothing is playing.")

    def track_finished(self, player):
        print("Nothing is playing.")


class AudioPlayer:
    def __init__(self, tracks: int):
        self.tracks_left = tracks
        self.state: PlayerState = (
            StoppedState() if tracks > 0 else EndedState()
        )

    def set_state(self, new_state: PlayerState) -> None:
        self.state = new_state

    # Every action is delegated to the current state
    def play(self) -> None:
        self.state.play(self)

    def pause(self) -> None:
        self.state.pause(self)

    def track_finished(self) -> None:
        self.state.track_finished(self)


player = AudioPlayer(tracks=2)
player.pause()           # Nothing is playing.
player.play()            # Starting playlist.
player.pause()           # Paused.
player.play()            # Resuming.
player.track_finished()  # Next track. 1 left.
player.track_finished()  # Playlist ended.
player.play()            # Playlist ended. Add tracks to play again.

Adding EndedState touched only PlayingState (which decides when to go there) and the constructor. No other state changed.

Example 2: document workflow#

The same shape works for any workflow with review steps. Here a document moves from draft to moderation to published, and can be sent back.

from abc import ABC, abstractmethod


class DocumentState(ABC):
    @abstractmethod
    def publish(self, doc: "Document") -> None: ...

    @abstractmethod
    def reject(self, doc: "Document") -> None: ...


class Document:
    def __init__(self, name: str):
        self.name = name
        self._state: DocumentState = DraftState()  # initial state

    def set_state(self, state: DocumentState) -> None:
        self._state = state

    def publish(self) -> None:
        self._state.publish(self)

    def reject(self) -> None:
        self._state.reject(self)


class DraftState(DocumentState):
    def publish(self, doc: Document) -> None:
        print(f"[{doc.name}] Draft → Moderation")
        doc.set_state(ModerationState())

    def reject(self, doc: Document) -> None:
        print(f"[{doc.name}] Can't reject a draft")


class ModerationState(DocumentState):
    def publish(self, doc: Document) -> None:
        print(f"[{doc.name}] Approved → Published")
        doc.set_state(PublishedState())

    def reject(self, doc: Document) -> None:
        print(f"[{doc.name}] Rejected → back to Draft")
        doc.set_state(DraftState())


class PublishedState(DocumentState):
    def publish(self, doc: Document) -> None:
        print(f"[{doc.name}] Already published")

    def reject(self, doc: Document) -> None:
        print(f"[{doc.name}] Can't reject a published document")


doc = Document("Report.pdf")
doc.publish()  # Draft → Moderation
doc.reject()   # Rejected → back to Draft
doc.publish()  # Draft → Moderation
doc.publish()  # Approved → Published
doc.publish()  # Already published

Example 3: cyclic states#

Some state machines are simpler still. When every state has exactly one next state, a single next() action moves the cycle along. A traffic light works this way:

from abc import ABC, abstractmethod


class LightState(ABC):
    @abstractmethod
    def next(self, light: "TrafficLight") -> None: ...


class TrafficLight:
    def __init__(self):
        self._state: LightState = RedState()

    def set_state(self, state: LightState) -> None:
        self._state = state

    def change(self) -> None:
        self._state.next(self)


class RedState(LightState):
    def next(self, light: TrafficLight) -> None:
        print("Red: STOP")
        light.set_state(GreenState())


class GreenState(LightState):
    def next(self, light: TrafficLight) -> None:
        print("Green: GO")
        light.set_state(YellowState())


class YellowState(LightState):
    def next(self, light: TrafficLight) -> None:
        print("Yellow: SLOW")
        light.set_state(RedState())


light = TrafficLight()
for _ in range(4):
    light.change()  # Red, Green, Yellow, Red

A music player (Stopped, Playing, Paused) works the same way, with three actions instead of one: play() in Paused resumes, pause() in Stopped prints "can't pause", stop() from anywhere returns to Stopped.

Template#

All three examples share one skeleton. Strip out the details and this is what's left:

from abc import ABC, abstractmethod


class State(ABC):
    @abstractmethod
    def handle(self, context: "Context") -> None: ...


class Context:
    def __init__(self):
        self._state: State = StateA()

    def set_state(self, state: State) -> None:
        self._state = state

    def request(self) -> None:
        self._state.handle(self)  # delegate


class StateA(State):
    def handle(self, context: Context) -> None:
        print("A handling; switching to B")
        context.set_state(StateB())  # the state controls the transition


class StateB(State):
    def handle(self, context: Context) -> None:
        print("B handling; switching to A")
        context.set_state(StateA())

Where you'll see state machines#

State machines are everywhere once you look for them.

  • Protocols: TCP connection states (Listen, Established, Closed), the textbook GoF example.
  • Workflows: loans, job applications, and the lifecycles below.
  • Devices: vending machines, ATMs (Idle, Card Inserted, PIN Entered), elevators, traffic lights, media players.
  • Games: character states (Idle, Running, Jumping, Attacking, Dead).
  • Libraries: packages such as transitions provide a framework for this in Python.

Business lifecycles follow the same idea. You can sketch each one as states in order:

Workflow States, in order
Order Placed, Paid, Shipped, Delivered
Support ticket Open, In Progress, Resolved, Closed
Subscription Trial, Active, Suspended, Canceled

When to use it#

State fits when:

  • An object's behavior depends heavily on its state, and it has several states.
  • Methods are full of conditionals on the same state field.
  • The states and transitions form a clear state machine that will likely grow.

When not to use it#

Skip it when:

  • There are only two or three states with trivial behavior. An Enum and a match statement are clearer.
  • The "state" is only data that doesn't change behavior.
  • A single boolean flag is enough.

Pitfalls#

Keep these in mind as the state machine grows.

  • Who owns transitions? Either the states decide (as above, flexible but spreads the transition map across classes) or the context does (centralized, but reintroduces conditionals). Pick one and stay consistent.
  • One class per state means more files; worth it only when the states carry real behavior.
  • Creating new state objects on every transition. Stateless state objects can be shared (made singletons or flyweights).
  • Forgetting invalid actions. Every state must handle every action, even if only to reject it. That's a feature: invalid transitions become explicit.

State vs similar patterns#

State shares its shape with several other patterns:

Pattern Difference
Strategy Same shape. A strategy is usually chosen by the client and rarely changes; states replace each other as the object runs
Command A command is an action ("play"); a state is a condition ("playing")
Bridge Bridge fixes the abstraction/implementation pairing up front; State swaps the implementation as state changes
Flyweight Often combined: share stateless state objects

Key takeaways#

  • One class per state; the context delegates every action to the current state object.
  • States trigger transitions by calling context.set_state(...), so the context passes itself in.
  • Adding a state means adding a class, not editing every method.
  • Every state handles every action, which makes invalid operations explicit.
  • Strategy and State share a structure; State is about the object changing its own behavior over time.
Revision notes · 2 min

Core idea#

State turns each state of an object into its own class. The context delegates every action to the current state object, and the states decide when to switch.

Key points#

  • It replaces an if/elif over a state field in every method.
  • Participants: the context (holds the current state), the state interface (one method per action), and concrete states.
  • The context passes itself to the state, so the state can call context.set_state(...) and read context data.
  • Adding a state means adding a class, not editing every method.
  • Every state handles every action, even if only to reject it. Invalid transitions become explicit.
  • Many LLD interview problems test this: vending machine, elevator, ATM, order lifecycle.
  • Examples: TCP connection states, traffic lights, document workflows, game characters, the transitions library.

Who owns transitions#

Owner Benefit Cost
The states Flexible Transition map spreads across classes
The context Centralized Brings conditionals back
  • Pick one owner and stay consistent.

State vs similar patterns#

Pattern Difference
Strategy Same shape; the client picks a strategy, but states replace each other as the object runs
Command A command is an action ("play"); a state is a condition ("playing")
Bridge Fixes the abstraction/implementation pairing up front; State swaps the implementation as state changes
Flyweight Often combined: share stateless state objects

Pitfalls#

  • One class per state means more files. Use it only when states carry real behavior.
  • Two or three trivial states? An Enum and a match statement are clearer.
  • Creating a new state object on every transition. Share stateless states as singletons or flyweights.
  • Forgetting to handle invalid actions in each state.

Say it in an interview#

  • "One class per state. The context delegates to the current state, and the state calls set_state."
  • "Strategy and State look alike. With State, the object changes its own behavior over time."

Found a mistake? Email ask@bigonotes.com