Design Patterns

Pattern 19 of 23, Behavioral family

State

Also known as: Objects for States

Let an object change its behavior when its internal state changes, as if it had changed class.

The problem

Document.publish() behaves differently in draft, in moderation or once published. The code turns into a huge switch (state) repeated in every method.

The solution

Extract each state into its own class implementing a common interface. The context delegates to its current state, and the states themselves decide on the transitions.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. Current state: Draft.
  2. The document delegates the call to its current state.
  3. Draft.publish() moves the document to moderation.
  4. Same method, different behavior: an admin approves.
  5. ModerationState โ†’ PublishedState: transition
  6. Already published: nothing happens. No if/else in Document.

An analogy

A smartphone: the same button unlocks it, wakes the screen or answers a call depending on the phone's state.

When to use it

  • State machines: orders, payments, workflows
  • Behavior that depends heavily on a status
  • Replacing big switch/if blocks on an enum

Pros and cons

Pros

  • Each state isolated and testable
  • Explicit transitions
  • Open/Closed: add a state without touching the others

Cons

  • Overkill for 2 simple states
  • Transitions scattered across several classes

Implementations

The same example, written idiomatically in each language.

State in Python

state.py 34 lines
class State:
    def publish(self, doc: "Document") -> None:
        raise NotImplementedError


class Draft(State):
    def publish(self, doc):
        doc.state = Moderation()


class Moderation(State):
    def publish(self, doc):
        if doc.user_is_admin:
            doc.state = Published()


class Published(State):
    def publish(self, doc):
        pass                          # already published


class Document:
    def __init__(self, admin: bool = False):
        self.state: State = Draft()
        self.user_is_admin = admin

    def publish(self):
        self.state.publish(self)      # delegate to the current state


doc = Document(admin=True)
doc.publish()
doc.publish()
print(type(doc.state).__name__)       # Published

State in TypeScript

state.ts 24 lines
interface State {
  name: string;
  publish(doc: Doc): void;
}

const Draft: State = { name: "draft", publish: (d) => (d.state = Moderation) };

const Moderation: State = {
  name: "moderation",
  publish: (d) => { if (d.isAdmin) d.state = Published; },
};

const Published: State = { name: "published", publish: () => {} };

class Doc {
  state: State = Draft;
  constructor(public isAdmin = false) {}
  publish() { this.state.publish(this); }
}

const doc = new Doc(true);
doc.publish();
doc.publish();
doc.state.name; // "published"

State in Java

state.java 24 lines
enum DocState {
    DRAFT {
        DocState publish(Doc d) { return MODERATION; }
    },
    MODERATION {
        DocState publish(Doc d) { return d.isAdmin() ? PUBLISHED : this; }
    },
    PUBLISHED {
        DocState publish(Doc d) { return this; }
    };

    abstract DocState publish(Doc d);
}

class Doc {
    private DocState state = DocState.DRAFT;
    private final boolean admin;

    Doc(boolean admin) { this.admin = admin; }

    boolean isAdmin() { return admin; }

    void publish() { state = state.publish(this); }
}

State in C#

state.cs 27 lines
abstract class DocState
{
    public abstract DocState Publish(Doc d);
}

class Draft : DocState
{
    public override DocState Publish(Doc d) => new Moderation();
}

class Moderation : DocState
{
    public override DocState Publish(Doc d) => d.IsAdmin ? new Published() : this;
}

class Published : DocState
{
    public override DocState Publish(Doc d) => this;
}

class Doc(bool isAdmin)
{
    public bool IsAdmin => isAdmin;
    public DocState State { get; private set; } = new Draft();

    public void Publish() => State = State.Publish(this);
}

State in PHP

state.php 27 lines
enum DocState: string
{
    case Draft = 'draft';
    case Moderation = 'moderation';
    case Published = 'published';

    public function publish(Doc $doc): self
    {
        return match ($this) {
            self::Draft      => self::Moderation,
            self::Moderation => $doc->isAdmin ? self::Published : $this,
            self::Published  => $this,
        };
    }
}

final class Doc
{
    public DocState $state = DocState::Draft;

    public function __construct(public bool $isAdmin = false) {}

    public function publish(): void
    {
        $this->state = $this->state->publish($this);
    }
}

State in Go

state.go 31 lines
type State interface {
    Publish(d *Doc) State
    Name() string
}

type draft struct{}

func (draft) Publish(*Doc) State { return moderation{} }
func (draft) Name() string       { return "draft" }

type moderation struct{}

func (m moderation) Publish(d *Doc) State {
    if d.IsAdmin {
        return published{}
    }
    return m
}
func (moderation) Name() string { return "moderation" }

type published struct{}

func (p published) Publish(*Doc) State { return p }
func (published) Name() string         { return "published" }

type Doc struct {
    State   State
    IsAdmin bool
}

func (d *Doc) Publish() { d.State = d.State.Publish(d) }

Frequently asked questions

What is the State design pattern?

Let an object change its behavior when its internal state changes, as if it had changed class. Extract each state into its own class implementing a common interface. The context delegates to its current state, and the states themselves decide on the transitions.

When should you use the State pattern?

State machines: orders, payments, workflows; Behavior that depends heavily on a status; Replacing big switch/if blocks on an enum.

What are the pros and cons of the State pattern?

Pros: Each state isolated and testable; Explicit transitions; Open/Closed: add a state without touching the others. Cons: Overkill for 2 simple states; Transitions scattered across several classes.