mediumConceptDesignMidSeniorStaff
When would you use the strategy pattern instead of inheritance?
Use the strategy pattern instead of inheritance when behaviour varies independently from object identity. Composition avoids subclass explosion, enables runtime swapping and makes algorithms easier to test.
5 min readUpdated 2026-08-15
Answer
Short answer
Use strategy when an algorithm varies independently from the object that uses it, especially when multiple axes of variation would create one subclass per combination. Inheritance is better when the type's identity itself varies along one stable hierarchy and the subclasses share meaningful state.
Was this answer helpful?
Likely follow-ups
- How does strategy differ from template method, given both let subclasses vary one step?
- What do you do when the strategy needs data that only the host object holds?
- When is a named strategy class worth more than a lambda?
- How would you select a strategy from configuration without a switch statement in the caller?
Related questions
- Where does encapsulation or polymorphism change a design, and how do you decide between composition and inheritance?mediumAlso on composition and inheritance6 min
- When would you use the observer pattern, and what goes wrong with it at scale?mediumAlso on behavioural-patterns4 min
- Give me a real single-responsibility violation you have seen, and how would you refactor it?mediumAlso on refactoring5 min
- Give me a subclass that the compiler accepts but that still breaks the Liskov substitution principle. What rule does it break?mediumAlso on inheritance5 min