Strategy Design Pattern

Strategy design pattern provides a family of algorithms. Each algorithm implements a single interface and all the algorithms are interchangeable. Client use the interface of the algorithm and can change the algorithm at runtime.

Strategy pattern provides loosely coupling between the client and the algorithms.

Structure

Strategy Pattern

Participants

IStrategy: Defines an algorithm contains all the abstract methods that must be implemented by all algorithms.

ConcreteStrategyA-A2-A3: Implements the IStrategy interface and defines it's own logic to writing algorithms.

Client: Have variable of IStrategy interface. Defines the logic to choose between different algorithms.

Example

Strategy Pattern Example

We have an ICompressStrategy interface which contains only one method Execute. ZipCompressStrategy and RarCompressionStrategy implements the ICompressStrategy interface.

Below is the implementation of above diagram in C#.

 

class Program
{
    static void Main(string[] args)
    {
        ICompressStrategy strategy = null;

        if(args[0] == "zip")
        {
            strategy = new ZipCompressionStrategy();
        }
        else if(args[0] == "rar")
        {
            strategy = new RarCompressionStrategy();
        }
        else //default
        {
            strategy = new RarCompressionStrategy();
        }
        var compressData = strategy.Compress("Compress Me");
        Console.WriteLine(compressData);
    }
}

public interface ICompressStrategy
{
    string Compress(string data);
}

public class ZipCompressionStrategy : ICompressStrategy
{
    public string Compress(string data)
    {
        return "<zip>" + data + "</zip";
    }
}

public class RarCompressionStrategy : ICompressStrategy
{
    public string Compress(string data)
    {
        return "<rar>" + data + "</rar>";
    }
}

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.