skip to content
Mohammad Rebati

Understanding the Strategy Design Pattern

/ 2 min read

Introduction to the Strategy Design Pattern

The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime. Instead of implementing a single algorithm directly, the code receives runtime instructions specifying which of a family of methods to use.

Key Concepts

  • Strategy Interface: This defines a common interface for all supported algorithms. Any algorithm that implements the interface can be used interchangeably by the client that utilizes the strategies.
  • Concrete Strategies: These are classes that implement the Strategy interface, providing specific behaviors.
  • Context: A class that contains a reference to a Strategy object. The context delegates the work to the strategy object instead of executing its own algorithm.

Benefits

  • Flexibility: Easily switch between different algorithms used by an object at runtime.
  • Decoupling: The high level of decoupling between the context and the strategies allows for better manageability and scalability.
  • Open/Closed Principle: You can introduce new strategies without changing the context’s code, adhering to this SOLID principle.

Example in Code

Here’s how you might implement the Strategy Pattern in C# for a simple application that can switch its behavior at runtime:

// Strategy interface
public interface IStrategy
{
void Execute();
}
// Concrete strategies
public class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing Strategy A");
}
}
public class ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing Strategy B");
}
}
// Context class
public class Context
{
private IStrategy _strategy;
public Context(IStrategy strategy)
{
this._strategy = strategy;
}
public void SetStrategy(IStrategy strategy)
{
this._strategy = strategy;
}
public void ExecuteStrategy()
{
_strategy.Execute();
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
var context = new Context(new ConcreteStrategyA());
context.ExecuteStrategy();
context.SetStrategy(new ConcreteStrategyB());
context.ExecuteStrategy();
}
}