Sitemap
Charles

Charles

Software developer, Entrepreneur, Writer

The Strategy Design Pattern in C#

5 min readJun 7, 2024

--

In this article, I will discuss Design Patterns and the strategy design pattern in C#.

What are Design patterns?

Design Patterns are reusable solutions to commonly occurring problems in software design.

If you’re a software engineer and haven’t yet explored software design patterns, now’s the perfect time to catch up!

There is a pattern for anything you want to achieve. You may have used one yourself without even knowing it, but it is a good idea to know about it because it makes your code mature, robust, testable, and reusable.

The software design pattern was introduced by four authors known as the Gang of Four, who published a book titled “Elements of Reusable Object-Oriented Software” which became so popular.

There are 23 design patterns that solve different problems. You don’t have to know all the design patterns, but it is better to get familiar with the famous ones and gradually introduce others as you practice them and apply them to your code. Design patterns also work hand in hand with the SOLID principles. Knowing the SOLID principles and Design patterns would make you a better software engineer but it is not mandatory to know the SOLID principles in order to work with Design Patterns

What is a Strategy Design Pattern

A strategy is a behavioural design pattern that allows you to define a family of algorithms and interchange their objects at runtime.

These algorithms are dispersed in various classes and communicate via a common interface. The client decides the implementation of the object to be used at runtime.

For example, you are creating an app that allows people to register their basic profile in order to gain access to use the application features. This was done successfully, but in the future, there was a new requirement to incorporate users work profiles.

To do this the developer would need to modify the existing code that already supports the basic profile creation to also suit the work profile requirements. By doing this, the class responsible for creating the basic profile would have to be modified which can break existing client and the class also need to be retested because of the new work profile requirements.

A solution to this problem is to create a separate class and define the algorithm (business logic) for the work profile creation. Therefore, the already existing class may not be modified and does not need to be retested because noting was changed.

This can be achieved by using a Strategy pattern.

To begin, a strategy interface is defined, from which all concrete strategies implement and extract their behaviours, as well as a context class, which has a reference to the concrete strategy and communicates only through the strategy interface.

You may have probably use the Strategy Pattern without even knowing it.

The context class is responsible for delegating work to a strategy via its interface defined in the constructor parameters.

Get Charles’s stories in your inbox

Join Medium for free to get updates from this writer.

The Strategy pattern improves your code by:

  • Writing less conditional statements
  • It supports the OCP principle by allowing you to create new strategies without modifying the existing strategies
  • It makes your code manageable and testable.

Structure of a Strategy

Press enter or click to view image in full size

To implement the Strategy pattern, we need to define:

  1. The Strategy Interface defines algorithms common to all concrete classes.
  2. The client decides the strategy to pass to the context
  3. The concrete strategies implement the various algorithms of the Strategy interface that the context class uses
  4. The context class is what the client uses to call the desired strategy at runtime. This class is responsible for delegating work to a strategy via its interface defined in the constructor parameters.

Building the User Profile Management App

Let’s create the profile management app we discussed about using the Strategy Design Pattern.

Step 1: Defining the Strategy Interface

 interface IProfile
{
object AddProfile(object data);
object GetProfile();
}

Step 2: Defining Concrete Classes that Implements the Strategy Interface

class BasicProfile : IProfile
{
List<object> items = null;
object IProfile.AddProfile(object data)
{
items = new List<object>
{
data
};
return items;
}

object IProfile.GetProfile()
{
return items ?? new List<object>();
}
}

The BasicProfile class implements the interface method AddProfile and GetPtofile. These methods are just responsible for adding a list of user profile object to a List and returning the objects from the list

 class JobProfile : IProfile
{
List<object> items = null;
object IProfile.AddProfile(object data)
{
items = new List<object>
{
data
};
return items;
}

object IProfile.GetProfile()
{
return items ?? new List<object>();
}
}

Now let’s create the context class that the client uses to call the desired strategy at runtime.

Step 3: The Context Class

 //the context class that has a reference to the concrete strategy and communicate only via the stategy interface
class UserProfile
{
IProfile profile;
public UserProfile(IProfile profile)
{
this.profile = profile;
}

public void AddProfile(object data)
{
Console.WriteLine($"Adding {Type.GetType(profile.ToString()).Name}");
this.profile.AddProfile(data);

}
public void GetProfile()
{
var result = this.profile.GetProfile();
var json = JsonConvert.SerializeObject(result);
Console.WriteLine(json);
}
}

The Context class defines a reference to the strategy interface in its constructor and it also defines method to add and get profile through the interface method.

Step 4: Running it

UserProfile profile = new UserProfile(new BasicProfile());
profile.AddProfile(new
{
Id = 1,
UserId = 1,
Fullname = "John Doe",
Email = "johndoe@gmail.com",
Phone = "12345",
Gender = "Male"
});
profile.GetProfile();

profile = new UserProfile(new JobProfile()); //let's work with job profile
profile.AddProfile(new
{
UserId = 1,
ExpectedSalary = 70000,
CV = "link to cv"
});
profile.GetProfile();

In the code snippet above, notice that the context class was instantiated and in its parameter, it wraps the BasicProfile class because that class implements the IProfile interface and the UserProfile context class references the IProfile Strategy Interface in its constructor.

So it is through the context class we can work with different variations of the strategies defined and not by instantiating the concrete strategy directly and instead of modifying existing strategies, we can create new concrete strategies that implements the strategy interface therefore adhering to the OCP principles and SRP.

Conclusion

I will be writing more about design patterns in C#, so don’t hesitate to follow me for more interesting topics.

Also Check out my article on SOLID principles in .NET or enrol for this Udemy course on Domain Driven Design in .NET Core that also introduces SOLID Principles and a modern architecture for building robust software in .NET Core.

Additionally, if you’re interested in learning a robust frontend framework, take a look at an all-in-one course covering Typescript, React, and NextJs. This course also includes a backend developed in .NET to further enhance your software development skills.

Happy coding!

--

--

Charles
Charles