Open In App

Strategy Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The strategy method is Behavioral Design pattern that allows you to define the complete family of algorithms, encapsulates each one and putting each of them into separate classes and also allows to interchange there objects. It is implemented in Python by dynamically replacing the content of a method defined inside a class with the contents of functions defined outside of the class. It enables selecting the algorithm at run-time. This method is also called as Policy Method.
 

Problem without using Strategy Method

Imagine you created an application for the departmental store. Looks simple? Initially, there was one and only one type of discount called the On-Sale-Discount. So. everything was going with ease and there was no difficulty for maintaining such a simple application for a developer but as time passes, the owner of the departmental store demands for including some other types of discount also for the customers. It is very easy to say to make these changes but definitely not very easy to implement these changes in an efficient way.
 

Solution using Strategy method


Let’s see how can we solve the above-described problem in an efficient way. We can create a specific class that will extract all the algorithms into separate classes called Strategy. Out actual class should store the reference to one of the strategy class.

Python3
"""A separate class for Item"""
class Item:

    """Constructor function with price and discount"""

    def __init__(self, price, discount_strategy = None):
        
        """take price and discount strategy"""
        
        self.price = price
        self.discount_strategy = discount_strategy
        
    """A separate function for price after discount"""

    def price_after_discount(self):
        
        if self.discount_strategy:
            discount = self.discount_strategy(self)
        else:
            discount = 0
            
        return self.price - discount

    def __repr__(self):
        
        statement = "Price: {}, price after discount: {}"
        return statement.format(self.price, self.price_after_discount())

"""function dedicated to On Sale Discount"""
def on_sale_discount(order):
    
    return order.price * 0.25 + 20

"""function dedicated to 20 % discount"""
def twenty_percent_discount(order):
    
    return order.price * 0.20

"""main function"""
if __name__ == "__main__":

    print(Item(20000))
    
    """with discount strategy as 20 % discount"""
    print(Item(20000, discount_strategy = twenty_percent_discount))

    """with discount strategy as On Sale Discount"""
    print(Item(20000, discount_strategy = on_sale_discount))

Output:

Price: 20000, price after discount: 20000
Price: 20000, price after discount: 16000.0
Price: 20000, price after discount: 14980.0

Class Diagram

Following is the class diagram for the Strategy Method

class-diagram-Strategy-method

class-diagram-Strategy-method

Advantages

  • Open/Closed principle: Its always easy to introduce the new strategies without changing the client’s code.
  • Isolation: We can isolate the specific implementation details of the algorithms from the client’s code.
  • Encapsulation: Data structures used for implementing the algorithm are completely encapsulated in Strategy classes. Therefore, the implementation of an algorithm can be changed without affecting the Context class
  • Run-time Switching: It is possible that application can switch the strategies at the run-time.

Disadvantages

  • Creating Extra Objects: In most cases, the application configures the Context with the required Strategy object. Therefore, the application needs to create and maintain two objects in place of one.
  • Awareness among clients: Difference between the strategies should be clear among the clients to able to select a best one for them.
  • Increases the complexity: when we have only a few number of algorithms to implement, then its waste of resources to implement the Strategy method.

Applicability 

  • Lot of Similar Classes: This method is highly preferred when we have a lot of similar classes that differs in the way they execute.
  • Conquering Isolation: It is generally used to isolate the business logic of the class from the algorithmic implementation.


Further Read – Strategy Method in Java


Previous Article
Next Article

Similar Reads

Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Strategy Method | JavaScript Design Pattern
Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the client to choos
8 min read
Strategy Method Design Pattern in Java
Strategy method or Strategy Design Pattern is a behavioral design pattern in Java that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It lets the client algorithm vary independently from the objects that use it. This pattern is useful when you have a family of algorithms and want to make them interchang
11 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
What is the Correlation Between System Design and Design Patterns?
System design and design patterns are closely related concepts in software engineering, with design patterns serving as reusable solutions to common design problems encountered during system design. System design and design patterns are interrelated concepts that work together to create robust and well-structured software systems. Important Topics
11 min read