Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 16, 2021 06:33 am GMT

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, abstractmethodfrom typing import Listclass Strategy(ABC):    @abstractmethod    def sort(self, elements):        passclass 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)

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() 

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.


Original Link: https://dev.to/karthikraja34/strategy-pattern-design-patterns-10cb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To