Author - StudySection Post Views - 27 views
Python Design

Strategy Method – Python Design Patterns

The strategy method is a Behavioral Design pattern that allows you to build an entire family of algorithms, encapsulates them all, separates them into classes, and lets you swap out their objects. It’s done in Python by dynamically substituting the data of methods declared within a class with the contents of functions written outside the class. It allows for algorithm selection at runtime. The Policy Procedure is another name for this method.

The problems without using the Strategy Method

Assume you’ve developed an app for a local business. Does it appear to be straightforward? Initially, the business was small, On-Sale-Discount was the only sort of discount available and some basic functionality. So. Everything was going smoothly, and maintaining such a simple application for a developer was not tough, but as time passed, the business grows and the owner of the business demanded more functionality and wants to add more forms of discounts to be included in the consumers. It is extremely simple to declare that certain changes should be made, but it is far more difficult to put them into action in a timely manner.

Solution using Strategy method

We can solve this problem in an effective and efficient way. We can construct a class called strategy class that will extract all of the algorithms into unique classes. The reference to one of the strategy classes should be stored in our real class.

Example:
"""
Define a collection of algorithms, encapsulate each one of them, and make them
interchangeable. Strategy lets the algorithm vary independently from the users that uses it.
"""
import abc
class Context:
def __init__(self, strategy):
self._strategy = strategy
def context_interface(self):
self._strategy.algorithm_interface()
class Strategy(metaclass=abc.ABCMeta):
@abc.abstractmethod
def algorithm_interface(self):
pass
class ConcreteStrategy(Strategy):
def algorithm_interface(self):
pass
def main():
strategy = ConcreteStrategy()
context = Context(strategy)
context.context_interface()
if __name__ == "__main__":
main()

Knowledge of .NET is quite rewarding in the IT industry. If you have got some skills in the .NET framework then a .NET certification from StudySection can prove to be a good attachment with your resume. You can go for a foundation level certificate as well as an advanced level certificate in the .NET framework.

Leave a Reply

Your email address will not be published.