DEV Community

Karthik Raja
Karthik Raja

Posted on • Edited on • Originally published at codewithkarthik.com

Strategy Pattern - Design Patterns

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.

from abc import ABC, abstractmethod
from typing import List

class Strategy(ABC):
    @abstractmethod
    def sort(self, elements):
        pass

class BubbleSortStrategy(Strategy):
    def sort(self, elements):
        # Sorting Logic
        print("Using Bubble Sort")
        return sorted(elements)

class InsertionSortStrategy(Strategy):
    def sort(self, elements):
        # Sorting Logic
        print("Using Insertion Sort")
        return sorted(elements)
Enter fullscreen mode Exit fullscreen mode

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.

class Sorter(object):
    def __init__(self, elements: List):
        self.elements = elements
        self._strategy = BubbleSortStrategy()

    def set_strategy(self, strategy: Strategy):
        self._strategy = strategy

    def sort(self):
        self.elements = self._strategy.sort(self.elements)
        print(self.elements)

if __name__=='__main__':
    a = Sorter([1, 6, 3, 2, 4, 8, 5, 7])
    a.sort()  # By default this uses bubble sorting algorithm
    a.set_strategy(InsertionSortStrategy())
    a.sort() 
Enter fullscreen mode Exit fullscreen mode

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 user logs in to a web app.

Top comments (0)