Welcome to our comprehensive guide on the Strategy Pattern in Python! This tutorial is designed to help both beginners and intermediates understand this powerful design pattern. Let's dive in!
The Strategy Pattern is a behavioral design pattern that enables an algorithm's behavior to be selected at runtime. It defines a family of algorithms, encapsulates each one, and makes them interchangeable.
In Python, the Strategy Pattern is often implemented using classes and inheritance. Here's a simple example:
from abc import ABC, abstractmethod
class Strategy(ABC):
@abstractmethod
def algorithm_interface(self):
pass
class ConcreteStrategyA(Strategy):
def algorithm_interface(self):
print("Implementation A")
class ConcreteStrategyB(Strategy):
def algorithm_interface(self):
print("Implementation B")
class Context:
def __init__(self, strategy: Strategy):
self.strategy = strategy
def execute_strategy(self):
self.strategy.algorithm_interface()
# Usage
context = Context(ConcreteStrategyA())
context.execute_strategy() # Output: Implementation AIn this example, we have Strategy as an abstract base class, and ConcreteStrategyA and ConcreteStrategyB are concrete strategies that implement the algorithm_interface method. The Context class uses a strategy and executes it through the execute_strategy method.
Let's make it more practical! Imagine we're building a shipping service application that supports multiple shipping strategies (e.g., economy, express, etc.). Each strategy has its own algorithm for calculating shipping costs.
class ShippingStrategy(Strategy):
def __init__(self, base_cost: float, cost_per_unit: float):
self.base_cost = base_cost
self.cost_per_unit = cost_per_unit
def algorithm_interface(self, number_of_units: int):
return self.base_cost + (self.cost_per_unit * number_of_units)
class ShippingContext:
def __init__(self, strategy: ShippingStrategy):
self.strategy = strategy
def calculate_shipping_cost(self, number_of_units: int):
return self.strategy.algorithm_interface(number_of_units)
# Usage
economy_strategy = ShippingStrategy(5, 2)
express_strategy = ShippingStrategy(10, 3)
shipping_context = ShippingContext(economy_strategy)
print(shipping_context.calculate_shipping_cost(5)) # Output: 25
shipping_context.strategy = express_strategy
print(shipping_context.calculate_shipping_cost(5)) # Output: 35In this example, we have ShippingStrategy and ShippingContext that implement the Strategy Pattern. The ShippingStrategy class calculates shipping costs based on the number of units, and the ShippingContext class uses a shipping strategy to calculate the shipping cost.
What is the main purpose of the Strategy Pattern?
That's it for this tutorial on the Strategy Pattern in Python! We hope you found it helpful and engaging. Stay tuned for more lessons on Python and other programming concepts. Happy coding! 💡🎯📝