SOLID & Design Patterns Interview Question #59
What is the difference between Strategy and State patterns?
Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate
Quick Interview Answer
Strategy and State can have similar class structures because both delegate behavior to interchangeable objects. Their intent differs: Strategy represents a chosen algorithm, while State represents behavior that changes as an object's internal state changes.
Detailed Explanation
Strategy and State can have similar class structures because both delegate behavior to interchangeable objects. Their intent differs: Strategy represents a chosen algorithm, while State represents behavior that changes as an object's internal state changes.
A strategy is often selected externally by configuration or a caller. State transitions are usually part of the object's lifecycle and domain rules.
Code Example
Strategy:
Checkout -> ITaxStrategy
State:
Order -> DraftState
-> PaidState
-> ShippedState