SOLID & Design Patterns Interview Question #24
How does the Strategy Pattern support the Open/Closed Principle?
SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner
Quick Interview Answer
With Strategy, new behavior can often be added by creating another implementation of the strategy interface. The context continues to depend on the abstraction and does not need a new branch for every algorithm.
Detailed Explanation
With Strategy, new behavior can often be added by creating another implementation of the strategy interface. The context continues to depend on the abstraction and does not need a new branch for every algorithm.
This supports OCP when strategies are selected through composition or a suitable resolver. If the resolver itself becomes a large switch that changes constantly, the variation has only been moved rather than fully designed.
Code Example
public class ShippingService
{
private readonly IShippingStrategy _strategy;
public ShippingService(IShippingStrategy strategy)
{
_strategy = strategy;
}
public decimal GetCost(decimal weight)
=> _strategy.Calculate(weight);
}