The Strategy Pattern: Swappable Algorithms
The Strategy pattern encapsulates interchangeable algorithms, allowing you to swap execution behaviors at runtime without changing the consumer class ♟️.
def json_formatter(data): return f"{{\"data\": \"{data}\"}}"
def csv_formatter(data): return f"data\r\n{data}"
class ReportContext:
def __init__(self, strategy):
self.strategy = strategy
def render(self, content):
return self.strategy(content)
ctx = ReportContext(json_formatter)
print(ctx.render("Hello World"))
# 119. The Strategy Pattern: Swappable Algorithms The Strategy pattern encapsulates interchangeable algorithms, allowing you to swap execution behaviors at runtime without changing the consumer class ♟️. ```python def json_formatter(data): return f"{{\"data\": \"{data}\"}}" def csv_formatter(data): return f"data\r\n{data}" class ReportContext: def __init__(self, strategy): self.strategy = strategy def render(self, content): return self.strategy(content) ctx = ReportContext(json_formatter) print(ctx.render("Hello World")) ``` Because Python treats functions as first-class objects, the Strategy pattern is often implemented simply by passing functions as arguments without boilerplate classes! ♟️ --- ### Question What is the primary motivation for adopting the Strategy pattern? 🧠 - [ ] a. To swap algorithms or processing behaviors at runtime without changing the consuming class ♟️ - [ ] b. To lock CPU core affinity to a single process - [ ] c. To convert recursive loops into while loops automatically - [ ] d. To eliminate the need for function return statements --- ### Challenge Write class `PaymentProcessor` initialized with `strategy`. Define `pay(self, amount)` that returns `self.strategy(amount)`. Test with strategy `lambda a: f'Paid ${a}'`. Print `processor.pay(50)`. 🎯 <details> <summary>Solution</summary> ```python class PaymentProcessor: def __init__(self, strategy): self.strategy = strategy def pay(self, amount): return self.strategy(amount) processor = PaymentProcessor(lambda a: f"Paid ${a}") print(processor.pay(50)) ``` </details>