Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
C++

C++

Zero-cost abstractions and full control over memory.

Paradigm
Multi-paradigm, OOP, generic
Typing
Static, strong-ish
Memory
Manual / RAII, no GC
Runs
Native machine code (AOT)
Concurrency
Threads, atomics, coroutines (C++20)
Behavioral pattern

State

Intent

Lets an object alter its behaviour when its internal state changes, as if it changed its class.

Problem

A document's publish() behaves differently in draft, moderation and published states; conditionals spread everywhere.

Solution

Move state-specific behaviour into state classes; the context delegates to the current state.

Real-world analogy

Think of it like this

A phone's buttons do different things when it is locked, unlocked or low on battery.

Structure

association / extends implements / depends on
Context - state: State+ changeState(s: State)+ doThis() 14 «interface» State + doThis()+ doThat() 2 ConcreteStates - context+ setContext(c)+ doThis() 3 Client

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Context — Context stores a reference to the current state and delegates state-specific work to it.
  2. 2State — State declares the state-specific methods.
  3. 3ConcreteStates — Concrete States implement behaviour for one state and may trigger transitions.
  4. 4Context — Both the context and the states can switch the current state.

Code example

A C++ code sample for State is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use State when behaviour depends on many states that change often.

Use State when massive conditionals on state fields.

Pros and cons

Pros

  • Single Responsibility per state
  • Removes bulky conditionals

Cons

  • Overkill for a few simple states

Relations with other patterns

Check yourself

Check yourself

A vending machine behaves differently when idle, waiting for payment, dispensing or out of stock.

Saved in this browser only. Part of Behavioral patterns (0/11).