Course contentsShow
← C#
Lesson 192 of 1,9082. Object-Oriented Design in C#Free lesson

Strategy Pattern for Modular Algorithms

You will swap interchangeable algorithms at runtime by injecting strategy objects into a context class.

Strategy Pattern for Modular Algorithms

In this lesson, you will learn how to make your code flexible by swapping entire algorithms at runtime using the Strategy Pattern.

The Problem of Hard-Coded Logic

Imagine you are building an InvoiceProcessor that calculates tax. If you use if or switch statements to switch between "US Tax," "EU Tax," or "No Tax," your class becomes bloated and difficult to change. If you want to add a new tax rule, you have to modify the existing InvoiceProcessor class, which violates the principle of keeping your code modular.

The Strategy Solution

The Strategy Pattern solves this by defining a common interface for a family of algorithms. You encapsulate each algorithm into its own class, then pass the specific strategy you need into your "Context" class.

Think of it like a printer: the printer is the Context, and the "Print Job" is the Strategy. You can swap out a Word document for a PDF without changing the printer itself.

// 1. Define the Strategy Interface
public interface ITaxCalculationStrategy {
    decimal Calculate(decimal amount);
}

// 2. Concrete Strategy A
public class USTaxStrategy : ITaxCalculationStrategy {
    public decimal Calculate(decimal amount) => amount * 0.08m;
}

// 3. Concrete Strategy B
public class EUTaxStrategy : ITaxCalculationStrategy {
    public decimal Calculate(decimal amount) => amount * 0.20m;
}

// 4. The Context class that uses the Strategy
public class InvoiceProcessor {
    private ITaxCalculationStrategy _strategy;

    // We inject the strategy here (Dependency Injection)
    public void SetStrategy(ITaxCalculationStrategy strategy) => _strategy = strategy;

    public void Process(decimal amount) {
        var tax = _strategy.Calculate(amount);
        Console.WriteLine($"Tax: {tax}");
    }
}

Runtime Flexibility

Because the InvoiceProcessor works with the ITaxCalculationStrategy interface rather than a specific class, you can change the tax behavior while the application is running. You simply call SetStrategy() whenever you need to swap the logic. This keeps your classes small, testable, and strictly focused on their own responsibilities.

Key Takeaway: The Strategy Pattern lets you define a family of algorithms, encapsulate each one as a separate class, and swap them interchangeably at runtime to keep your logic decoupled and modular.