SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 26 / 42

Middle

What is the State pattern, how does it differ from Strategy, and when is an enum + switch enough?

Short answer

State: an object changes behaviour with its current state; each state is a class that decides the next transition itself (PENDING → PAID → SHIPPED). Strategy has the same structure but the caller picks the algorithm.

State Strategy
Who picks the implementation the states themselves (they move between each other) the caller / configuration
Do implementations know each other? yes, they return the next state no
Changes during the object's life constantly usually fixed per call

3 points to say:

  1. States decide their own transitions.
  2. The caller picks a Strategy.
  3. With few states, an enum is enough.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.