How to use Strategy Design Pattern

Sriram Kumar Mannava
2 min readApr 30, 2023

--

What is Strategy Design Pattern?

Strategy Pattern is a Behavioral Design Pattern.

It lets you define a family of algorithms in separate classes and make their objects interchangeable.

It can be used when you need to create multiple variations for a solution and let the calling client decide which variation of the algorithm needs to be called over the runtime.

Strategy pattern separates each variant of an algorithm into a separate strategy and let the client run the required strategy by passing the respective instance during runtime.

A Context maintains an instance of a concrete strategy algorithm and communicates only via the strategy interface.

Each solution has a concrete strategy implemented for each variation of the algorithm.

How to implement a Strategy pattern?

For a given set of algorithms, you can design a Strategy as below -

1. Define an abstract strategy that has a common method to contain the algorithm

2. Each variation of the algorithm is represented by a concrete strategy which implements the abstract strategy

3. Define a context class that maintains an instance of the strategy to be applied. All the interactions that happen within the context class is through the abstract strategy type and not any concrete strategy type.

4. A calling client creates an instance of this context class and passes the strategy it wants to use. The context runs the business logic and uses the strategy set by the client.

Implementing Strategy Pattern with an Example

The following code explains implementing Strategy with C#

Full article — https://referbruv.com/blog/understanding-strategy-design-pattern-made-easy/

#designpatterns #strategy #oops #cleancode #design #dotnetcore #coding

--

--

Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger