Course contentsShow
← Software Engineering
Lesson 313 of 1,9339. Behavioral Design PatternsFree lesson

Strategy vs State Pattern

Understand when to use Strategy for algorithm selection versus State for object behavior changes based on internal state.

Strategy vs State Pattern

You'll learn: how to decide between Strategy and State patterns by understanding their different purposes in behavioral design.


Core Distinction

Both Strategy and State look structurally similar—they both encapsulate behavior in separate classes and use delegation—but their intent differs fundamentally:

Strategy Pattern is about selecting an algorithm from a family of interchangeable algorithms. The client (or context) chooses which strategy to use, and strategies don't know about each other. The choice is usually made once or changed externally based on preferences or configuration.

State Pattern is about managing object behavior that changes based on internal state. The state objects manage transitions themselves, and behavior changes automatically as state evolves. The context doesn't choose states—states emerge from the object's lifecycle.

When to Use Each

Use Strategy When:

  • You need to swap algorithms at runtime (e.g., different sorting methods, payment processors)
  • The behavior choice is external or configuration-driven
  • Algorithms are independent and don't trigger each other

Use State When:

  • An object's behavior changes dramatically based on what state it's in
  • State transitions follow specific rules or a lifecycle
  • You're replacing complex conditional logic that checks "current state"

Analogy

Strategy: Choosing a travel mode (car, train, plane) to reach your destination. You decide once based on preferences.

State: A traffic light changing from green → yellow → red. Each state determines what happens next automatically.

Key Takeaway:
Use Strategy when you need to select between interchangeable algorithms externally; use State when an object's behavior must change automatically based on its evolving internal state.