Strategy Design Pattern in Python
What is Strategy Design Pattern?
The Strategy design pattern is used when we have multiple algorithms that can be used to solve a problem and we want to be able to switch between these algorithms without changing the client code that's using them. This pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.
Example
Here's a python example of strategy design pattern:
# Define the strategy interface
class Strategy:
def calculate(self, a, b):
pass
# Implement the strategies
class AddStrategy(Strategy):
def calculate(self, a, b):
return a + b
class MultiplyStrategy(Strategy):
def calculate(self, a, b):
return a * b
# Define the context that will use the strategy
class Calculator:
def __init__(self, strategy):
self.strategy = strategy
def calculate(self, a, b):
return self.strategy.calculate(a, b)
# Use the context with different strategies
add_strategy = AddStrategy()
calculator = Calculator(add_strategy)
result = calculator.calculate(5, 10)
print(result) # Output: 15
multiply_strategy = MultiplyStrategy()
calculator.strategy = multiply_strategy
result = calculator.calculate(5, 10)
print(result) # Output: 50
What's happening in this code?
In this example, we define the Strategy
interface which the different strategies will implement. Then, we implement two different strategies: AddStrategy
and MultiplyStrategy
. These strategies both have their own implementation of the calculate
method.
We then define the Calculator
class which will use the strategy to perform calculations. The Calculator
class has a calculate
method which takes in two parameters, a
and b
, and then uses the strategy to perform the calculation.
We create an instance of the AddStrategy
and pass it to the Calculator
instance. We then call calculate
on the calculator instance with the values 5 and 10, which will use the AddStrategy
implementation to perform the calculation and return the result.
Next, we create an instance of the MultiplyStrategy
and set it as the strategy for the calculator instance. We then call calculate again with the values 5 and 10, but this time the MultiplyStrategy
implementation is used to perform the calculation, which returns the result of 50.