skip to content

State Pattern - Behavior Changes Based on Internal State

Updated: at 12:00 AM

1. The Problem

Problem: Behavior Changes Based on Internal State

Some systems behave differently depending on their current state. Example: a document lifecycle — Draft → Moderation → Published.

A naïve implementation encodes state as conditionals:

if state == "draft":
    ...
elif state == "moderation":
    ...
elif state == "published":
    ...

As states grow, this leads to:

The core issue: state-dependent behavior is mixed with control logic.

We need behavior to change automatically when state changes — without if/else.

2. The State Pattern: Behavior Is a Function of State

The State Pattern solves this by making state explicit as an object.

Core idea:

Instead of asking “what state am I in?”, the context asks the state to act.

A system using State has two parts:

The context does not branch on state. The state controls behavior and transitions.

You get:

Use State when:

3. Implementation: State + Context in Python

State interface

from abc import ABC, abstractmethod

class DocumentState(ABC):
    @abstractmethod
    def publish(self, document):
        pass

Concrete states

class DraftState(DocumentState):
    def publish(self, document):
        document.set_state(ModerationState())
        return "Document moved to moderation"
class ModerationState(DocumentState):
    def publish(self, document):
        document.set_state(PublishedState())
        return "Document published"
class PublishedState(DocumentState):
    def publish(self, document):
        return "Document is already published"

Each state:

Context

class Document:
    def __init__(self):
        self._state = DraftState()

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

    def publish(self):
        return self._state.publish(self)

Usage

doc = Document()

doc.publish()  # Draft → Moderation
doc.publish()  # Moderation → Published
doc.publish()  # No-op

No conditionals. Behavior changes by swapping the state object.

4. Strategy vs State (Critical Distinction)

They look similar structurally. They are not conceptually the same.

AspectStrategyState
PurposeChoose algorithmModel state-dependent behavior
Who switches?Client / externalState itself
TriggerConfiguration / runtime choiceInternal transitions
FocusHow to do somethingWhat is allowed now

Rule of thumb:

If transitions matter → State. If algorithms are interchangeable → Strategy.

5. When to Use State (and When Not To)

You likely need State when you notice:

Common pitfalls:

Avoid State if: