Strategy Design Pattern in C#

Strategy Design Pattern in C# with Real-time Example

In this article, I am going to discuss the Strategy Design Pattern in C# with examples. Please read our previous article where we discussed the Visitor Design Pattern in C# with real-time examples. The Strategy Design Pattern falls under the category of Behavioural Design Pattern. As part of this article, we are going to discuss the following pointers in detail.

  1. What is the Strategy Design Pattern?
  2. Understanding the Strategy Design Pattern with Real-time Example.
  3. Implementing the Strategy Design Pattern in C#.
  4. When do we need to use the Strategy Design Pattern in real-time applications?
What is the Strategy Design Pattern?

According to Gang of Four Definitions, define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

The Strategy Design Pattern is used when we have multiple algorithms (solutions) for a specific task and the client decides the actual implementation to be used at runtime.

In simple words, we can say that the Strategy Design Pattern (also called policy pattern) attempts to solve the issue where you need to provide multiple solutions for the same problem so that one can be selected at runtime.

To understand the above explanation better, please have a look at the following image. As shown in the below diagram we have one task and to solve the task we have three solutions (i.e. Solution 1, Solution 2 and Solution 3). That means using the above three solutions we can achieve the task. As per the Strategy Design Pattern which solution should be used that will be decided by the client only at runtime. So, the client will decide whether to use Solution 1 to achieve the task or solution 2 to achieve the task or solution 3 to achieve the task at run time.

What is the Strategy Design Pattern in C#?

Understanding the Strategy Design Pattern with Real-time Example:

Let us understand the strategy design pattern using one real-time example. Please have a look at the following image. As you can see, in my D drive I have a folder called DotNetDesignPattern and within that folder, multiple text files are there. My business requirement is, I have to compress this DotNetDesignPattern folder and send the compressed file to the client.

For this requirement, I have two solutions. The first solution is, I can compress the folder into rar format and send it to the client and the second solution is, I can compress the folder into zip format and sends it to the client. So, for the above requirement, I have two solutions.

Strategy Design Pattern with Real-time Example in C#

As per the strategy design pattern, for the particular problem (task) there are multiple solutions and which solution to be used will be decided by the client at runtime. So, in our example, the client will decide at runtime in which format he wants the file.

How to implement the Strategy Design Pattern in C#?

Let us discuss the step by step procedure to implement the above example using the Strategy Design Pattern in C#.

Step1: Creating Abstract Strategy

Create an interface with the name ICompression and then copy and paste the following code in it. The Strategy declares an interface that is common to all supported algorithms. The Context object uses this interface to call the algorithm defined by a ConcreteStrategy

namespace StrategyDesignPattern
{
    public interface ICompression
    {
        void CompressFolder(string compressedArchiveFileName);
    }
}
Step2: Creating concrete Strategy

Each concrete strategy by which we will compress a file item must be implementing the method CompressFolder of ICompression interface. Let’s create two concrete strategy classes as per our business requirement.

RarCompression:

Create a class file with the name RarCompression.cs and then copy and paste the following code in it.

using System;
namespace StrategyDesignPattern
{
    public class RarCompression : ICompression
    {
        public void CompressFolder(string compressedArchiveFileName)
        {
            Console.WriteLine("Folder is compressed using Rar approach: '" + compressedArchiveFileName
                 + ".rar' file is created");
        }
    }
}
ZipCompression:

Create a class file with the name ZipCompression.cs and then copy and paste the following code in it.

using System;
namespace StrategyDesignPattern
{
    public class ZipCompression : ICompression
    {
        public void CompressFolder(string compressedArchiveFileName)
        {
            Console.WriteLine("Folder is compressed using zip approach: '" + compressedArchiveFileName
                 + ".zip' file is created");
        }
    }
}
Step3: Creating context

Create a class file with the name CompressionContext.cs and then copy and paste the following code in it. This context class contains a property that is used to hold the reference of a Strategy object. This property will be set at run-time by the client according to the algorithm that is required.

namespace StrategyDesignPattern
{
    public class CompressionContext
    {
        private ICompression Compression;
        
        public CompressionContext(ICompression Compression)
        {
            this.Compression = Compression;
        }

        public void SetStrategy(ICompression Compression)
        {
            this.Compression = Compression;
        }

        public void CreateArchive(string compressedArchiveFileName)
        {
            Compression.CompressFolder(compressedArchiveFileName);
        }
    }
}
Step4: Client

Modify the Main method as shown below.

using System;
namespace StrategyDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            CompressionContext ctx = new CompressionContext(new ZipCompression());
            ctx.CreateArchive("DotNetDesignPattern");

            ctx.SetStrategy(new RarCompression());
            ctx.CreateArchive("DotNetDesignPattern");

            Console.Read();
        }
    }
}

Output:

How to implement the Strategy Design Pattern in C#?

The Participant involved in the Strategy Design Pattern:

As already shown in the example, there are three participants involved in the Strategy Design Pattern. Their role and responsibility as follows:

  1. Strategy (ICompression): The Strategy declares an interface that is going to be implemented by all supported algorithms.
  2. ConcreteStrategy (RarCompression and ZipCompression): These are classes and they implement the algorithm defined by the Strategy (ICompression) interface.
  3. Context (CompressionContext): This is a class which maintains a reference to a Strategy object, and then uses that reference to call the algorithm defined by a particular ConcreteStrategy (i.e. either RarCompression or ZipCompression).
When do we need to use the Strategy Design Pattern in real-time applications?
  1. When there are multiple solutions for a given task and the selection criteria of a solution defined at run-time.
  2. When you want different variants of an algorithm.
  3. When many related classes differ only in their behavior.
  4. When a class defines many behaviors and these appear as multiple conditional statements in its operations. Instead of many conditional statements, move-related conditional branches into their own strategy class.
  5. When an algorithm uses data that the client shouldn’t know about. Use the Strategy Design Pattern to avoid exposing the complex and algorithm-specific data structures.

In the next article, I am going to discuss the Strategy Design Pattern Real-time Example- Travel using C#. Here, in this article, I try to explain the Strategy Design Pattern step by step with some examples. I hope you understood the need and use of the Strategy Design Pattern in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *