Strategy Design Pattern Using C#

This pattern falls under the category of behavioral pattern and as the name suggests, it allows clients to choose an algorithm from a set of algorithms at run time.

Strategy pattern defines a family of algorithms, encapsulates each one of them and makes them interchangeable at run time within that family.

Now let’s understand what each one of them actually means.

  1. Family of Algorithms: This means this pattern provides a set of algorithms using one of which at run time you can achieve the desired output.
  2. Encapsulate each one of the: This pattern allows you to place your algorithms in different classes (encapsulate them).
  3. Makes the algorithm interchangeable: The beauty with strategy pattern is that we can select at run time which algorithm we want to apply to our object and can also replace them with one another.

These are the three main points of Strategy pattern. I hope we are clear with the above- discussed points. So, let’s understand one real -world scenario where it can be really helpful to use.

Example

Suppose you want to go from one place to another and you want to see how much time it will take you to reach your destinations if you use different modes of transport. In this case you can implement the Strategy Pattern.

Let’s now see the UML diagram and then we will go deep into the code to see how actually it works.

Strategy Design Pattern Using C#
Image source: Wikipedia

Clearly here we see the below things,

  • An Interface called Strategy which has a method called execute () .
  • Concrete Strategy classes A and B which implement that Interface.
  • Lastly one Context class using which we can use different concrete strategies at run time.

As per our example, IStrategy is the interface which looks something like,

  1. public interface IStrategy {  
  2.     string GetTravelTime(string source, string destination);  
  3. }  

We have 3 Concrete Strategy classes which implement IStrategy interface and these classes can have their own logic to calculate the time.

  1. public class CarStrategy: IStrategy {  
  2.     public string GetTravelTime(string source, string destination) {  
  3.         return "It takes 40 minutes to reach from " + source + " to " + destination + " using Car.";  
  4.     }  
  5. }  
  6. public class BikeStrategy: IStrategy {  
  7.     public string GetTravelTime(string source, string destination) {  
  8.         return "It takes 25 minutes to reach from " + source + " to " + destination + " using Bike.";  
  9.     }  
  10. }  
  11. public class BusStrategy: IStrategy {  
  12.     public string GetTravelTime(string source, string destination) {  
  13.         return "It takes 60 minutes to reach from " + source + " to " + destination + " using Bus.";  
  14.     }  
  15. }  

Lastly, we have one Context class called TravelStrategy using which a client can select any strategy at run-time.

  1. public class TravelStrategy {  
  2.     private IStrategy _strategy;  
  3.     public TravelStrategy(IStrategy chosenStrategy) {  
  4.         _strategy = chosenStrategy;  
  5.     }  
  6.     public void GetTravelTime(string source, string destination) {  
  7.         var result = _strategy.GetTravelTime(source, destination);  
  8.         Console.WriteLine(result);  
  9.     }  
  10. }  

Our main program looks like:

  1. void Main() {  
  2.     Console.WriteLine("Hello!, Please select the mode of transport to get the travel time between source and destination: \nCar \nBike \nBus");  
  3.     var userStrategy = Console.ReadLine().ToLower();  
  4.     Console.WriteLine("\nUser has selected *" + userStrategy + "* as mode of transport\n");  
  5.     Console.WriteLine("\n*****************************************************************************************************\n");  
  6.     switch (userStrategy) {  
  7.         case "car":  
  8.             new TravelStrategy(new CarStrategy()).GetTravelTime("Point A""Point B");  
  9.             break;  
  10.         case "bike":  
  11.             new TravelStrategy(new BikeStrategy()).GetTravelTime("Point A""Point B");  
  12.             break;  
  13.         case "bus":  
  14.             new TravelStrategy(new BusStrategy()).GetTravelTime("Point A""Point B");  
  15.             break;  
  16.         default:  
  17.             Console.WriteLine("You have chosen an invalid mode of transport.");  
  18.             break;  
  19.     }  

OUTPUTS

  1. When user selects car as the preferred mode of transport

    Strategy Design Pattern Using C#

    Output

    Strategy Design Pattern Using C#

  2. When user selects bike as the preferred mode of transport

    Strategy Design Pattern Using C#

    Output

    Strategy Design Pattern Using C#

  3. When user selects bus as the preferred mode of transport

    Strategy Design Pattern Using C#

    Output

    Strategy Design Pattern Using C#
  4. When user selects anything else as the preferred mode of transport

    Strategy Design Pattern Using C#

    Output

    Strategy Design Pattern Using C#
When to use this pattern?

Use this pattern when there are multiple similar classes that only differ in terms of how they execute the behavior.

Some common use cases

  • Giving different permissions depending on role and department.
  • Giving discount depending on different conditions/coupons/happy hours etc.
  • It can be used in games, considering the surrounding conditions player can either swim (In water), trek (on mountain), jump (hurdles) or walk (on road).
Further readings:
 
Learn more about other design patterns here: Design Pattern in .NET
 
 
I hope you find this article helpful. Stay tuned for more … Cheers!!