This content originally appeared on Level Up Coding - Medium and was authored by Okan Yenigün
Implementation of Strategy Pattern in Python
The strategy design pattern is one of the behavioral design patterns. Behavioral design patterns deal with the assignment of responsibilities or algorithms that classes will have. While doing this, it also helps communication between the classes. It is mostly used to manage change.
Previous episode:
Design Patterns in Python: Bridge Pattern
A family of algorithms consists of objects that undertake similar tasks but differ in one aspect ,and each one can be interchangeable. Thanks to the strategy design pattern, we can relocate these objects independently of the client who will use any object from this family.
Such families of algorithms often lead to if-else hell if a design is deployed without a pattern. Because a concept that has been branched once is scalable, meaning that as the business grows and expands, new methods are bound to be found or needed. In this way, the family will expand and the client’s demands will be more diverse.
We need to break the if-else structures. The client must be independent of any algorithms. Otherwise, it is against both Single Responsibility Principle and Open Close Principle.
Code
As an example, let’s apply this design pattern in the sales decision part of an automated trading application, in a very simplified way.
We have an application class that works with the client. It uses various sales strategies according to the situation. Depending on the situation, it may need to use any of these sales strategies. The sales interface class contains a method: sell_crypto. In our case, 3 different sales strategies implement this interface as concrete classes.
A = TradingApp()
assets = A.sell_order(SellLittle())
print(assets)
#Out: {'btc': 90.0, 'usdt': 300000.0}
assets = A.sell_order(SellHalf())
print(assets)
#Out: {'btc': 45.0, 'usdt': 1350000.0}
Conclusion
An abstract relationship is established between the client and the algorithm or methods to be used with the strategy pattern. The client can move towards different behaviors as it wishes and the system is not affected by this. New algorithms can be easily added to the family.
References
https://refactoring.guru/design-patterns/strategy
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
Design Patterns in Python: Strategy Pattern was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Okan Yenigün
Okan Yenigün | Sciencx (2022-07-04T11:48:20+00:00) Design Patterns in Python: Strategy Pattern. Retrieved from https://www.scien.cx/2022/07/04/design-patterns-in-python-strategy-pattern/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.