What is the Strategy pattern?
Quick Answer
Strategy defines a family of interchangeable algorithms behind a common interface and lets you pick one at run time. Instead of a growing switch that decides how to calculate shipping, you have IShippingCalculator with StandardShipping, ExpressShipping, FreeShipping, and you inject or select the one you need.
Strategy is about making an algorithm pluggable. If I've got a method that does a big switch to work out shipping cost or a discount, that's a smell — every new rule means editing that method. With Strategy I define IShippingCalculator, put each rule in its own class, and select or inject the right one. It's the standard way to hit Open/Closed: new behaviour is a new class, not a change to old code. In C# a lightweight version is just passing a Func instead of defining an interface.
It's the classic way to satisfy the Open/Closed Principle: add a new algorithm by adding a class, not by editing existing code. Structure:
- An interface for the operation (
IPricingRule). - Concrete strategies implementing it.
- A context that holds a strategy and delegates to it — often just a consumer that receives the strategy via constructor injection.
In C#, a simple strategy can be a Func<> delegate rather than a full interface. Related: the State pattern has the same shape but the object changes its own strategy as its state changes.