Strategy Pattern

Prakash Sharma
2 min readNov 5, 2022

--

This is the fourth blog in my series of must-know design patterns. Today we will be understanding the use case of the strategy pattern.

Problem statement :
Implement a file storage that performs multiple tasks before storing the image in the database. There can be multiple tasks such as compression, encryption, hashing, etc that could be done before storing the task. We have to implement a system that should be extensible, so if tomorrow I decide to perform any other task then the system should support it with minimum changes.

The basic approach could be something like this —

The above method will work but there are a few problems with this implementation -

  • The job of this class is to store the image and apply the given task. But if we watch carefully we can see this class is also keeping the logic of task creation and application. So we can say the class is having more than one responsibility and it violates the Single Responsibility Principle.
  • The class is not extensible so if we have to add any other task then we have to modify the class and write all the logic there.
  • The size of the class will increase with the number of tasks it gonna handle.

How do we fix it?

Here, we can use the strategy pattern to solve the problem. Strategy pattern helps us to deal with the area of code that changes prone. It lets you define the family of algorithms into different classes and make their object interchangeable.

We have to provide the abstraction over the tasks which is gonna change in the future, so if we know that multiple variants of compression algorithm can be added in the future then we can provide the abstraction of the compression objects and the same for the rest.

Let’s see how can we achieve that —

Create the required interface of each kind of task

Now create the required concrete implementations. we will create two encryption algorithm and two compression for the demo purpose

Now, Implement the FileStorage class as follow

So this class is so sleek compared to the above implementation and it avoids the responsibility of doing multiple tasks on its own by delegating to the concrete implementations of the class.

This class follows an open-closed principle so if tomorrow we have to add any other compression algorithm we can simply create a class by extending Compression interface and we are good to go to use that implementation without modifying the FileStorage class.

Result section -

So, we have implemented the strategy pattern. Do clap if you learned something today and if you have any suggestions/queries use the comment section.

My previous design pattern blogs —

--

--