The Strategy pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it. Here's an example of how you can implement the Strategy pattern in C#:
using System;
// Strategy interface
public interface IStrategy
{
void Execute();
}
// ConcreteStrategyA class
public class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Executing strategy A");
}
}
// ConcreteStrategyB class
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();
}
}
// Client code
class Program
{
static void Main()
{
// Create strategies
IStrategy strategyA = new ConcreteStrategyA();
IStrategy strategyB = new ConcreteStrategyB();
// Create context with strategyA
Context context = new Context(strategyA);
// Execute strategyA
context.ExecuteStrategy();
// Change the strategy to strategyB
context.SetStrategy(strategyB);
// Execute strategyB
context.ExecuteStrategy();
}
}
In this example:
IStrategy is the strategy interface that declares the Execute method.
ConcreteStrategyA and ConcreteStrategyB are concrete implementations of the IStrategy interface, each providing a different algorithm.
Context is the class that uses a strategy. It has a reference to the IStrategy interface and can switch between different strategies at runtime.
In the Main method, two strategies (ConcreteStrategyA and ConcreteStrategyB) are created. The Context is initially set with ConcreteStrategyA and then switched to ConcreteStrategyB. Calling ExecuteStrategy on the context will execute the currently set strategy.
This pattern allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. Clients can then use a strategy without knowing its implementation details, promoting flexibility and maintainability.
#AbdurRahimRatulAliKhan #ARRAK #Code #Programming #CodeDescription #Strategy #DesignPatterns