Python: Strategy Design pattern
Strategy is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside the original context object.
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
UML diagram.
let's see one simple example.
In the following, we have a payment context, where we can use any payment method to make a payment.
we have created a payment type strategy interface by defining a protocol class. And the defined different payment types like Visa, Mastercard, and RuPay.
In the future, if we need to add a new payment type then we can simply add the class Implementation of that type. There is no need to change the Payment context class. This is the main benefit of the strategy design patterns.
Conclusion:
With Strategy Design pattern:
- You can swap algorithms used inside an object at runtime.
- You can isolate the implementation details of an algorithm from the code that uses it.
- You can replace inheritance with composition.
- Open/Closed Principle. You can introduce new strategies without having to change the context.