05 Dec 2023
Intermediate
The Strategy design pattern is a behavioral pattern that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It allows the client to choose the appropriate algorithm at runtime. In C#, the Strategy pattern typically involves the following main components:
-
Strategy Interface:
- Declares an interface common to all supported algorithms.
- Typically, this interface consists of a single method, often named something like
ExecuteorPerformAlgorithm.
public interface IStrategy { void Execute(); } -
Concrete Strategies:
- Implement the
IStrategyinterface with specific algorithms. - Each concrete strategy provides a different implementation of the algorithm.
public class ConcreteStrategyA : IStrategy { public void Execute() { Console.WriteLine("Concrete Strategy A executed"); } }public class ConcreteStrategyB : IStrategy { public void Execute() { Console.WriteLine("Concrete Strategy B executed"); } }public class ConcreteStrategyC : IStrategy { public void Execute() { Console.WriteLine("Concrete Strategy C executed"); } } - Implement the
-
Context:
- Maintains a reference to the current strategy object.
- Allows the client to switch between strategies at runtime.
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(); } } -
Client:
- Creates an instance of the context and sets its initial strategy.
- Can switch between different strategies during runtime.
class Client { static void Main() { IStrategy strategyA = new ConcreteStrategyA(); IStrategy strategyB = new ConcreteStrategyB(); IStrategy strategyC = new ConcreteStrategyC(); Context context = new Context(strategyA); context.ExecuteStrategy(); context.SetStrategy(strategyB); context.ExecuteStrategy(); context.SetStrategy(strategyC); context.ExecuteStrategy(); } }
In this example:
IStrategyis the interface that declares the common operation for all concrete strategies.ConcreteStrategyA,ConcreteStrategyB, andConcreteStrategyCare concrete implementations of the strategy interface, each providing a different algorithm.Contextis the class that maintains a reference to the current strategy and allows the client to switch between strategies at runtime.- The
Clientcreates instances of the concrete strategies and the context, sets the initial strategy for the context, and can dynamically switch between different strategies during runtime.
The Strategy pattern allows the client to vary its behavior by choosing from a family of algorithms at runtime. It promotes flexibility and enables the easy addition of new algorithms without modifying the client code.