Design Patterns interview question · Most asked
What is the difference between the Strategy and State patterns?
Summary
Both delegate to an interchangeable object, but in Strategy the client chooses the algorithm and strategies don't know each other, while in State the state objects themselves trigger transitions to other states as the object's lifecycle progresses.
Longer Answer
Strategy answers "how should this be done?" (shipping cost: standard, express); the choice is usually made once from configuration or user input. State answers "what is allowed right now?" (an order that is pending, then paid, then shipped); behaviour changes as the object moves through states, and the states know their successors.
Their class diagrams look almost identical; the difference is who changes the delegate and why.
Key Points
- Same structure, different intent.
- Strategy: chosen by the client, independent.
- State: transitions driven by states.
- Strategy = how; State = what's allowed now.
Deep dive: Design Patterns, Explained Simply: Choosing the Right Pattern
Explanation
What interviewers look for
Clear intent difference with an example of each.
More most-asked Design Patterns questions
- What problem does the Builder pattern solve? Show an example.
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- What is the difference between dependency inversion, dependency injection and inversion of control?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- How do you implement a Singleton, and why is it often considered an anti-pattern?