Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Template Method - Python Design Patterns
Next article icon

Strategy Method - Python Design Patterns

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
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


Next Article
Template Method - Python Design Patterns
author
chaudhary_19
Improve
Article Tags :
  • Python
  • Design Pattern
  • System Design
  • python-design-pattern
Practice Tags :
  • python

Similar Reads

  • Python Design Patterns Tutorial
    Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
    8 min read
  • Creational Software Design Patterns in Python

    • Factory Method - Python Design Patterns
      Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the cli
      4 min read
    • Abstract Factory Method - Python Design Patterns
      Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group
      4 min read
    • Builder Method - Python Design Patterns
      Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code
      5 min read
    • Prototype Method Design Pattern in Python
      The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuratio
      6 min read
    • Singleton Method - Python Design Patterns
      Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class
      5 min read
    • Structural Software Design Patterns in Python

      • Adapter Method - Python Design Patterns
        Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to cre
        4 min read
      • Bridge Method - Python Design Patterns
        The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to or
        5 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences