How does the Strategy pattern support OCP?
Answer
The Strategy pattern is one of the most direct implementations of OCP. It defines a family of algorithms, encapsulates each one in a class, and makes them interchangeable. The context class holds a reference to a strategy interface and delegates behavior to whichever implementation is injected. When a new algorithm is needed, you add a new strategy class without modifying the context. Example: a Sorter class that takes a SortStrategy interface can use BubbleSortStrategy, QuickSortStrategy, or any future strategy — the Sorter class itself never changes. This is OCP in action: the context is closed for modification but open for extension via new strategies. Spring's Comparator, Laravel's drivers, and payment gateways commonly follow this pattern.
Previous
How would you refactor a class that violates SRP?
Next
What are the conditions for LSP compliance?
More SOLID Principles Questions
View all →- Intermediate How would you refactor a class that violates SRP?
- Intermediate What are the conditions for LSP compliance?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?
- Intermediate How does SOLID relate to GRASP principles?