Strategy Pattern in C#: What It Is and How It Works
Strategy Pattern in C# is a design pattern that lets you define a family of algorithms, put each one in a separate class, and make them interchangeable. It allows the behavior of a class to be changed at runtime by switching the algorithm it uses without changing the class itself.How It Works
Imagine you have a remote control that can change the way a robot moves: it can walk, run, or jump. Instead of building a new robot for each movement, you just change the remote's setting. The Strategy Pattern works like this remote control. It separates different ways of doing something into separate classes called strategies.
In C#, you create an interface that defines a method for the behavior you want to change. Then, you make different classes that implement this interface with different algorithms. The main class holds a reference to the interface and can switch between these strategies at runtime, making the behavior flexible and easy to extend.
Example
This example shows a simple calculator that can perform addition or multiplication. The operation can be changed at runtime using the Strategy Pattern.
using System; // Strategy interface public interface IOperation { int Execute(int a, int b); } // Concrete strategy for addition public class AddOperation : IOperation { public int Execute(int a, int b) => a + b; } // Concrete strategy for multiplication public class MultiplyOperation : IOperation { public int Execute(int a, int b) => a * b; } // Context class public class Calculator { private IOperation _operation; public Calculator(IOperation operation) { _operation = operation; } public void SetOperation(IOperation operation) { _operation = operation; } public int Calculate(int a, int b) { return _operation.Execute(a, b); } } class Program { static void Main() { Calculator calculator = new Calculator(new AddOperation()); Console.WriteLine("Add: " + calculator.Calculate(5, 3)); calculator.SetOperation(new MultiplyOperation()); Console.WriteLine("Multiply: " + calculator.Calculate(5, 3)); } }
When to Use
Use the Strategy Pattern when you have multiple ways to perform a task and want to switch between them easily without changing the main code. It is helpful when you want to avoid long if-else or switch statements that select behavior.
For example, in a payment system, you might have different payment methods like credit card, PayPal, or cryptocurrency. Using the Strategy Pattern, you can add new payment methods without changing the core payment processing code.
Key Points
- The Strategy Pattern defines a family of algorithms and makes them interchangeable.
- It uses interfaces to separate the algorithm from the context.
- It helps to change behavior at runtime without modifying the context class.
- It promotes open/closed principle by allowing new strategies without changing existing code.