Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Behavioural Patterns
Lessons in this course (18)

10. Strategy

Basic★ Must knowLesson 10 of 18

Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.

csharp
public interface IShippingCost { string Mode { get; } decimal Calculate(decimal weightKg); }
public class Standard : IShippingCost { public string Mode => "standard"; public decimal Calculate(decimal w) => 50 + w * 10; }
public class Express : IShippingCost { public string Mode => "express"; public decimal Calculate(decimal w) => 120 + w * 25; }

public class ShippingService(IEnumerable<IShippingCost> strategies)
{
    public decimal Quote(string mode, decimal kg) => strategies.Single(s => s.Mode == mode).Calculate(kg);
}

The most common answer to "how do you remove a big switch statement?". Also: IComparer<T> passed to Sort is a strategy.