Strategy Pattern in Python: Write Flexible, Clean Code
How to pick different algorithms at runtime—without a tangled web of if/else
Hey there! Today I want to write about a design pattern: the Strategy Pattern. Perfect for when you have multiple ways to solve the same problem and you want clean, maintainable code.
Why the Strategy Pattern?
Let’s start with a scenario: imagine you're building a pizza delivery app, and different restaurants have wildly different APIs. Without planning, you might end up stuffing your code full of branching logic. Instead, the Strategy Pattern lets you isolate each integration into its own “strategy,” making your code neat and flexible.
In software design terms, a strategy defines a family of algorithms, each encapsulated in its own class (or callable), and they’re all interchangeable at runtime. This helps avoid massive if/else blocks and makes adding new behavior super easy without touching existing code—hello open/closed principle!
The Problem with if/else Hell
Before we bring in the Strategy Pattern, let’s look at the “naive” way of solving this problem. You might write a function that tries to handle every restaurant API in one place
def order_pizza(api_type: str, pizza_type: str, quantity: int):
if api_type == "fancy":
print(
f"[FancyPizzaAPI] Sending JSON payload: {{'pizza': '{pizza_type}', 'qty': {quantity}}}"
)
elif api_type == "oldschool":
print(f"[OldSchoolPizzaAPI] Sending XML: {pizza_type}{quantity}")
elif api_type == "superfast":
print(
f"[SuperFastPizzaAPI] Sending plain text: ORDER {pizza_type.upper()} x{quantity}"
)
else:
raise ValueError("Unknown API type")
This works fine if you only have two or three cases. But as soon as you need to integrate more restaurants, this function becomes a mess of branching logic. Every new API means editing this function, risking bugs in existing logic. It’s not modular, it’s not extensible, and it violates the open/closed principle. That’s exactly the pain point the Strategy Pattern is designed to solve.
Example
Here is an example of how one might solve the pizza delivery scenario:
from abc import ABC, abstractmethod
# --- Strategy Interface ---
class RestaurantAPI(ABC):
"""Common interface for all restaurant integrations"""
@abstractmethod
def place_order(self, pizza_type: str, quantity: int) -> None:
pass
# --- Concrete Strategies ---
class FancyPizzaAPI(RestaurantAPI):
def place_order(self, pizza_type: str, quantity: int) -> None:
print(
f"[FancyPizzaAPI] Sending JSON payload to /order: {{'pizza': '{pizza_type}', 'qty': {quantity}}}"
)
class OldSchoolPizzaAPI(RestaurantAPI):
def place_order(self, pizza_type: str, quantity: int) -> None:
print(
f"[OldSchoolPizzaAPI] Sending XML: {pizza_type} {quantity} "
)
class SuperFastPizzaAPI(RestaurantAPI):
def place_order(self, pizza_type: str, quantity: int) -> None:
print(
f"[SuperFastPizzaAPI] Sending plain text: ORDER {pizza_type.upper()} x{quantity}"
)
# --- Context ---
class PizzaDeliveryService:
"""Holds a reference to a RestaurantAPI strategy"""
def __init__(self, api_strategy: RestaurantAPI):
self._api_strategy = api_strategy
def set_strategy(self, api_strategy: RestaurantAPI):
"""Switch to a different restaurant API at runtime"""
self._api_strategy = api_strategy
def order_pizza(self, pizza_type: str, quantity: int):
self._api_strategy.place_order(pizza_type, quantity)
# --- Example Usage ---
if __name__ == "__main__":
# Start with FancyPizzaAPI
service = PizzaDeliveryService(FancyPizzaAPI())
service.order_pizza("Margherita", 2)
# Switch to OldSchoolPizzaAPI
service.set_strategy(OldSchoolPizzaAPI())
service.order_pizza("Pepperoni", 1)
# Switch to SuperFastPizzaAPI
service.set_strategy(SuperFastPizzaAPI())
service.order_pizza("Hawaiian", 3)
What’s Going On?
Now that we’ve seen the code, let’s break down how the Strategy Pattern is applied in our pizza delivery app. We’ll look at the roles of each piece and how they work together to keep our code clean and adaptable.
-
Strategy (
RestaurantAPI) – An interface that declares the methodplace_order, which every restaurant integration must implement. -
Concrete Strategies –
FancyPizzaAPI,OldSchoolPizzaAPI, andSuperFastPizzaAPIeach implementplace_orderin their own way (JSON, XML, plain text). -
Context (
PizzaDeliveryService) – Holds a reference to a strategy object and delegatesorder_pizzacalls to it. -
Runtime Swapping – We can call
set_strategyto switch to a different restaurant API without changing the rest of our code.
if/else
chains and ensures you’re following the open/closed principle: your code is open
for extension but closed for modification.
When Should You Use It?
The Strategy Pattern is especially useful in situations where you have several different ways to achieve the same goal, and you want to switch between them without cluttering your code. For example, you might need to apply different sorting, filtering, or validation logic depending on user input or a configuration setting. In an e-commerce application, you could use it to manage multiple pricing or discount rules, allowing each to be encapsulated as its own strategy. It also comes in handy when exporting data in various formats—such as CSV, JSON, or XML—where each format is handled by a dedicated export strategy. Even payment processing can benefit: credit cards, PayPal, and bank transfers can each be implemented as interchangeable strategies, making it easy for the client to pick one at runtime without touching the underlying business logic. In each of these cases, the Strategy Pattern keeps your code modular, flexible, and ready to grow without turning into a maintenance nightmare.
A Lightweight Alternative: Functions as Strategies
One cool thing about Python is that functions are first-class citizens. That means we don’t always need full-blown classes to represent a strategy—sometimes a simple function is enough. Here’s a function-based version of our pizza delivery service:
# --- Function-based strategies ---
def fancy_pizza_order(pizza_type: str, quantity: int):
print(
f"[FancyPizzaAPI] Sending JSON payload: {{'pizza': '{pizza_type}', 'qty': {quantity}}}"
)
def oldschool_pizza_order(pizza_type: str, quantity: int):
print(f"[OldSchoolPizzaAPI] Sending XML: {pizza_type}{quantity}")
def superfast_pizza_order(pizza_type: str, quantity: int):
print(
f"[SuperFastPizzaAPI] Sending plain text: ORDER {pizza_type.upper()} x{quantity}"
)
# --- Context using functions ---
class PizzaDeliveryService:
def __init__(self, order_strategy):
self._order_strategy = order_strategy
def set_strategy(self, order_strategy):
self._order_strategy = order_strategy
def order_pizza(self, pizza_type: str, quantity: int):
self._order_strategy(pizza_type, quantity)
# --- Example usage ---
service = PizzaDeliveryService(fancy_pizza_order)
service.order_pizza("Margherita", 2)
service.set_strategy(oldschool_pizza_order)
service.order_pizza("Pepperoni", 1)
This version is short, flexible, and feels very “Pythonic.” The function-based approach is great when your strategies are simple, independent, and stateless. The class-based Strategy Pattern (what we built earlier) is more appropriate when strategies get complex, need shared state, or must follow a strict interface.
How Do I Know I Should Use It?
Ask yourself:
- Do I have different ways to accomplish the same task?
- Is there lots of branching logic (if/else or switch) spread across my code?
- Do I anticipate adding new behavior variants in the future?
If you answered yes, the Strategy Pattern can clean that up by isolating behaviors, simplifying maintenance, and making your decisions explicit.
Also note that too many tiny strategy classes can feel over-engineered for simple tasks. Keep strategy interfaces minimal and strategies stateless when possible. Let Context manage state.
Wrapping Up
I hope this short walkthrough helps you see how the Strategy Pattern can make your code cleaner and more flexible. Next time you’re tempted to write a ton of if/else logic, consider isolating variations as strategies. It's a neat way to keep your code modular and future‑friendly.
Feel free to ask more questions if you want to dig deeper.
Happy coding!
Comments
Post a Comment