Strategy
Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Context
Shipping calculation can be done by weight, by zone, or by flat rate. The rules change depending on the customer.
Problem
A giant if statement for each shipping method grows out of control and violates OCP.
Solution
An IShippingStrategy interface with an implementation for each algorithm. The client receives the strategy via injection.
#Example in C#
public interface IShippingStrategy { decimal Calculate(Order o); }
public class FlatRate : IShippingStrategy { public decimal Calculate(Order o) => 5m; }
public class ByWeight : IShippingStrategy { public decimal Calculate(Order o) => o.Weight * 0.8m; }
public class ByDistance : IShippingStrategy { public decimal Calculate(Order o) => o.KmToDestination * 0.05m; }
public class Checkout
{
private readonly IShippingStrategy _shipping;
public Checkout(IShippingStrategy s) => _shipping = s;
public decimal Total(Order o) => o.Subtotal + _shipping.Calculate(o);
}When NOT to use it
- When there's only one strategy.
- When algorithms share significant state: the pattern artificially fragments.
Tradeoffs
| Pro | Con |
|---|---|
| Complies with OCP | More classes |
| Client injects the strategy | Client must know when to use which |
#behavioral #gof