top of page
Writer's pictureSunil Kumar Yadav

Strategy: Must Know Design Pattern (6/7)


The Strategy Pattern is a design pattern in object-oriented programming that falls under the category of behavioral patterns. It is used to define a family of algorithms, encapsulate each one of them, and make them interchangeable. This pattern allows a client to choose the appropriate algorithm from a family of algorithms at runtime.


Strategy pattern defines family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Strategy pattern is used when we have multiple algorithms for a specific task and the client decides the actual implementation to be used at runtime.

Let's try to understand strategy patterns with the help of a simple example. Consider we want to implement a filter that can be used in various ways like to filter out odd numbers, even numbers, positive numbers, or negative numbers. In order to implement a filter class, we would like to maintain the open-closed principle so that future extension is possible.


from abc import ABC, abstractmethod

class FilterStrategy(ABC):
    """ Abstract method which defines the interface. 
        Concrete class needs to implement abstract method.
    """
    @abstractmethod
    def removeValue(self,value):
        pass   # implentation needed in concrete class

class RemoveNegativeStrategy(FilterStrategy):
    def removeValue(self,value):
        return value < 0

class RemoveOddStrategy(FilterStrategy):
    def removeValue(self,value):
        return abs(value) % 2

class Values:
    def  __init__(self, vals):
        self.vals = vals    # list of value

    def  filter(self, strategy):
        res = []
        for n in self.vals:
            if not strategy.removeValue(n):
                res.append(n)
        return res

values = Values([1, -4, 6, 9, 8, -2])

print(values.filter(RemoveNegativeStrategy()))  # prints [1, 6, 9, 8]
print(values.filter(RemoveOddStrategy()))       # prints [-4, 6, 8, -2]

In the above example, we've used the abstract class FilterStrategy to define interfaces for various filtering methods. Various filtering methods that we are supporting will adhere to the interface defined by the abstract base class FilterStrategy. We've added two algorithms to filter out negative values and odd values from the given list. Abstract base class ensures future extension of our solution.


Inside the client code, based on the needs of the user, they can select an appropriate algorithm to filter out values.


Where Strategy pattern is used?

The Strategy Pattern is used in various software design scenarios where you want to decouple an algorithm from its client and provide flexibility to switch between different implementations of that algorithm. Here are some common use cases where the Strategy Pattern can be applied:

  1. Sorting Algorithms: You can use the Strategy Pattern to implement different sorting algorithms (e.g., bubble sort, quicksort, merge sort) and allow the user to choose which algorithm to use at runtime.

  2. Payment Processing: You can use the Strategy Pattern to implement different payment methods (e.g., credit card, PayPal, cryptocurrency) and select the payment method dynamically.

  3. File Compression: When working with files, you can use the Strategy Pattern to implement different compression algorithms (e.g., ZIP, GZIP, RAR) and choose the compression method as needed.

  4. Graphics Rendering: In graphics libraries, you can use the Strategy Pattern to implement various rendering strategies for different shapes, colors, or rendering techniques.

  5. Authentication: When dealing with authentication, you can have multiple authentication strategies (e.g., username/password, OAuth, API key), and the Strategy Pattern allows you to switch between them as required.

  6. Travel Booking: For travel booking systems, you can implement different pricing strategies for flights, hotels, or car rentals and select the appropriate pricing strategy.

  7. Communication Protocols: When working with network protocols, you can use the Strategy Pattern to switch between different communication strategies (e.g., HTTP, WebSocket, TCP/IP).

  8. Text Editors: Text editors can use the Strategy Pattern to implement various text formatting or processing strategies (e.g., Markdown, HTML, plain text) for document rendering.

In general, the Strategy Pattern is beneficial in any situation where you have multiple interchangeable algorithms or behaviors, and you want to make these algorithms easily extensible, maintainable, and changeable without altering the code that uses them. It promotes the "open-closed principle" from the SOLID principles, which encourages software components to be open for extension but closed for modification.



63 views0 comments

Recent Posts

See All

Commentaires


bottom of page