BehavioralC#verifiedVerified

Strategy Pattern in C#

Defines a family of algorithms, encapsulates each one, and makes them interchangeable so the algorithm can vary independently from the clients that use it.

How to Implement the Strategy Pattern in C#

1Step 1: Define the strategy interface

public interface ISortStrategy<T>
{
    T[] Sort(T[] data);
}

2Step 2: Concrete strategies

public class BubbleSort<T> : ISortStrategy<T> where T : IComparable<T>
{
    public T[] Sort(T[] data)
    {
        var arr = (T[])data.Clone();
        for (var i = 0; i < arr.Length - 1; i++)
            for (var j = 0; j < arr.Length - i - 1; j++)
                if (arr[j].CompareTo(arr[j + 1]) > 0)
                    (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
        return arr;
    }
}

public class QuickSort<T> : ISortStrategy<T> where T : IComparable<T>
{
    public T[] Sort(T[] data)
    {
        var arr = (T[])data.Clone();
        QuickSortImpl(arr, 0, arr.Length - 1);
        return arr;
    }

    private static void QuickSortImpl(T[] arr, int lo, int hi)
    {
        if (lo >= hi) return;
        var pivot = arr[hi];
        var i = lo;
        for (var j = lo; j < hi; j++)
            if (arr[j].CompareTo(pivot) < 0)
                (arr[i], arr[j]) = (arr[j], arr[i++]);
        (arr[i], arr[hi]) = (arr[hi], arr[i]);
        QuickSortImpl(arr, lo, i - 1);
        QuickSortImpl(arr, i + 1, hi);
    }
}

3Step 3: Context uses the strategy

public class Sorter<T>(ISortStrategy<T> strategy)
{
    public T[] Sort(T[] data) => strategy.Sort(data);
}

Strategy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Strategy Pattern in the Real World

Consider a GPS app offering route options: fastest, shortest, or avoid tolls. The destination is the same, but the navigation algorithm changes based on your preference. The app (context) simply hands the journey off to whichever routing strategy you selected; you can switch strategies mid-trip without the app needing to change its structure.