Strategy Design Pattern in C#

Strategy design pattern comes under behavioral design pattern category of Gang of four (GoF) design patterns. This article explains what is strategy pattern and how to implement strategy design pattern in C#.

Strategy Design Pattern

Using strategy pattern, client can select their preferred algorithm from a family of algorithms to perform some operation. Each algorithm will be encapsulated in different classes and can be accessed using a common interface.  The strategy design pattern can have divided in three parts:

  • Define multiple algorithms
  • Encapsulate Each algorithm as an object
  • Algorithms can be interchangeable at runtime for the end user

Gang of Four(GoF) Definition:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Strategy Design Pattern – UML Diagram

strategy design pattern in c# -uml diagram

Participants in above UML diagram are:

  • IStrategy: This is the common interface for all algorithms.
  • ConcreteStrategy: This class implements Istrategy This class implements the actual algorithm.
  • Context: This class maintains a reference of ConcreteStrategy Client will use this class to use the algorithms.

Strategy Design Pattern in C# – Example

Let’s implement a simple example to understand strategy design pattern in C#.

Problem Statement

Consider an application which encodes the given string. There are three encryption algorithm available to encode the give value and end user or client can use any one of them.  The encoding algorithm will be selected at runtime. The encryption algorithms are RAS Algorithm, DES Algorithm and Blowfish Algorithm.

Class Diagram

strategy design pattern in C# - Class diagram

Participants in above UML diagram are:

  • IEncodingStrategy: IStrategy interface
  • RASEncodingStrategy: ConcreteStrategyA class
  • DESEncodingStrategy: ConcreteStrategyB class
  • BlowFishEncodingStrategy: ConcreteStrategyC class
  • Encoding: Context class

Strategy Design Pattern in C# – Implementation Code

Result

strategy design pattern in C# - output

Hope you get the idea about how to implement strategy design pattern in C#. Please post your comments for queries and feedback. Thanks for reading this article.

 

Share Button
The following two tabs change content below.
Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Gyanendu Shekhar

Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Leave a Reply

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