Strategy is a design pattern where a set of rules is defined and allows us to have different implementations.

For example, suppose we want to write a repository for reading data that allows us to change where the data is read (with minimal changes to the code) in the future. We can store data in Redis or InMemory. To achieve this, we first create an interface called ICacheRepository and then create classes named RedisCacheRepository and InMemoryCacheRepository that implement the methods of this interface. The ICacheRepository interface includes a method called Get, and classes inheriting from this interface must implement the Get method. 

public interface ICacheRepository
{
    string Get(string key);
}

RedisCacheRepository:

public class RedisCacheRepository : ICacheRepository
{
    public string Get(string key)
    {
        return "Get value from RedisCache" ;
    }
}

InMemoryCacheRepository:

public class InMemoryCacheRepository : ICacheRepository
{
    public string Get(string key)
    {
        return "Get value from InMemoryCache";
    }
}

Then, if we assign the RedisCacheRepository class to the ICacheRepository interface, when the Get method is called in our program, the value "Get value from RedisCache" will be returned. Similarly, when we assign the InMemoryCacheRepository class to the ICacheRepository interface, we will receive the value "Get value from InMemoryCache" when calling the Get method.

var cacheKey = "DotNetDocs";

ICacheRepository repository = new InMemoryCacheRepository();
Console.WriteLine(repository.Get(cacheKey)); //Get value from InMemoryCache

repository = new RedisCacheRepository();
Console.WriteLine(repository.Get(cacheKey)); //Get value from RedisCache

If you execute the written code, you will see the following output:

Get value from InMemoryCache
Get value from RedisCache

The purpose of this article was to present the Strategy design pattern in C# and the implementation of the classes InMemoryCacheRepository and RedisCacheRepository has not been done in reality (for reading data).
In the next article, a real implementation of the Strategy design pattern along with a Factory in an Asp.Net Core application will be presented.

Powered by Froala Editor

Comments