how to do strategy pattern in csharp

The Strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime. This pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

Here's how to implement the Strategy pattern in C#:

  1. Define the base strategy interface that declares a common method for executing an algorithm:
main.cs
public interface IStrategy
{
    void Execute();
}
51 chars
5 lines
  1. Create concrete strategy classes that implement the IStrategy interface:
main.cs
public class ConcreteStrategyA : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing algorithm using strategy A");
    }
}

public class ConcreteStrategyB : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing algorithm using strategy B");
    }
}
305 chars
16 lines
  1. Create a context class that holds a reference to the current strategy object:
main.cs
public class Context
{
    private IStrategy _strategy;

    public Context(IStrategy strategy)
    {
        _strategy = strategy;
    }

    public void ExecuteAlgrorithm()
    {
        _strategy.Execute();
    }
}
218 chars
15 lines
  1. Test the implementation by creating a context object with a specific strategy, and executing the algorithm:
main.cs
static void Main(string[] args)
{
    // create a context with strategy A
    var context = new Context(new ConcreteStrategyA());
    context.ExecuteAlgrorithm();

    // change the strategy to B at runtime
    context = new Context(new ConcreteStrategyB());
    context.ExecuteAlgrorithm();

    Console.Read();
}
315 chars
13 lines

gistlibby LogSnag