Behavioral

State

Allows an object to alter its behavior when its internal state changes.

State machinesWorkflow enginesGame AI

Understanding State

The State pattern allows an object to change its behavior when its internal state changes, making it appear as if the object changed its class. Instead of using large switch statements to handle different states, each state is encapsulated in its own struct implementing a common interface. In Go, the context struct holds a reference to the current state interface, and state transitions happen by swapping this reference. This is the clean way to implement state machines — from document workflows to TCP connection states to game character behaviors.

Key Concepts

  • State interface — defines the behavior methods that vary by state (e.g., Handle(), Process())
  • Concrete states — individual structs implementing state-specific behavior and transition logic
  • Context — the object whose behavior changes — holds a reference to the current state
  • State transitions — states may trigger transitions by calling context.SetState() to switch to a new state

When to Use

✅ Use when
  • • An object\'s behavior depends on its state and it must change at runtime
  • • You have complex conditional logic based on object state (many if/switch branches)
  • • You\'re implementing a state machine, workflow engine, or protocol handler
  • • State-specific behavior needs to be tested independently
⚠️ Avoid when
  • • You only have 2-3 states with simple behavior — a switch statement is clearer
  • • State transitions are fixed and don\'t need runtime flexibility
  • • The overhead of multiple state objects isn\'t justified by the complexity

Structure

Context (holds current state)
↓ delegates to
<<State Interface>>
↓ implements
StateA
StateB
StateC

How It Works

Context
Order
current: Pending
States
Pending
Processing
Shipped
Behavior depends on state
1

Context

Object behavior depends on its current state.

1 / 4

Basic Implementation

Simple state toggle:

main.go
Loading editor...

Real-World Example: Order Status

E-commerce order state machine:

main.go
Loading editor...