Skip to content
CodeWithKarthik

Strategy Pattern - Design Patterns

2 min read

In this post, I am going to talk about one of the popular design patterns - Strategy pattern. Before learning it let me give you a small introduction about what is a design pattern.

What are design patterns?

Design patterns are solutions for commonly occurring problems in software design. They heavily depend on object-oriented principles and are introduced by a group of programmers known as Gang of Four. There are totally 24 design patterns divided among categories such as

  • Creational patterns
  • Structural patterns
  • Behavioral patterns

Without further ado, let's see the strategy pattern.

According to Wikipedia, Strategy pattern helps in the selection of algorithm at runtime. This pattern lets the algorithm vary independently from clients that use it.

To explain the above, let me describe a most common problem and how it is handled using a strategy pattern

Problem

Let's say we are building an eCommerce application and we have multiple payment options such as credit card, debit card, PayPal, etc.., Another thing to note is we may get new payment options in the future.

For the above problem, We can create separate strategy classes for each payment option, and then finally we can create a class that would accept a payment algorithm and then let that algorithm decide how the user pays. Payment algorithm can be credit card, debit card, etc..,

The advantage in using the above approach is Whenever a new payment option comes, we can write a new payment algorithm class and then use that strategy.

Advantages

  • Follows clean code and Open-Closed principle
  • It is easy to switch between different algorithms/strategies in runtime.

Basic Implementation

Let's consider we have a list of elements which we need to sort. It should support any sorting algorithm.

1from abc import ABC, abstractmethod
2from typing import List
3
4class Strategy(ABC):
5 @abstractmethod
6 def sort(self, elements):
7 pass
8
9class BubbleSortStrategy(Strategy):
10 def sort(self, elements):
11 # Sorting Logic
12 print("Using Bubble Sort")
13 return sorted(elements)
14
15class InsertionSortStrategy(Strategy):
16 def sort(self, elements):
17 # Sorting Logic
18 print("Using Insertion Sort")
19 return sorted(elements)

In the above code, we created a base class Strategy that has abstract method sort . Now, whichever sorting algorithm we require should extend this class and implement the sort method. For the sake of simplicity, I have just printed which sorted algorithm we are using instead of actually sorting with that algorithm.

1class Sorter(object):
2 def __init__(self, elements: List):
3 self.elements = elements
4 self._strategy = BubbleSortStrategy()
5
6 def set_strategy(self, strategy: Strategy):
7 self._strategy = strategy
8
9 def sort(self):
10 self.elements = self._strategy.sort(self.elements)
11 print(self.elements)
12
13if __name__=='__main__':
14 a = Sorter([1, 6, 3, 2, 4, 8, 5, 7])
15 a.sort() # By default this uses bubble sorting algorithm
16 a.set_strategy(InsertionSortStrategy())
17 a.sort()

As you see in the above code, we created a class called Sorter which has the elements to be sorted, and also it has a method set_strategy we can provide an instance of SortingStrategy as input to that during runtime. It will use the provided strategy to sort the elements.

Conclusion

This pattern helps in choosing a specific algorithm from multiple algorithms. Passport js uses this pattern to select which authentication mechanism to use when a use

© 2021 by CodeWithKarthik. All rights reserved.
Theme by LekoArts