Course contentsShow
← Python
Lesson 484 of 1,0607. Object-Oriented ProgrammingFree lesson

Applying the Strategy Pattern for Swappable Algorithms

Encapsulate interchangeable algorithms into separate classes to allow runtime behavior changes without modifying the core logic of your objects.

In this lesson, you will learn how to use the Strategy Pattern to encapsulate interchangeable algorithms, allowing you to swap behaviors at runtime without modifying your core object logic.

The Problem: Rigid Logic

Imagine you are building a ShippingCalculator class. If you use a series of if/else statements to calculate costs based on different carriers (e.g., FedEx, UPS, or Drone), your class quickly becomes a maintenance nightmare. Adding a new shipping method would require you to crack open the ShippingCalculator class and modify its internal code, violating the principle of open/closed design.

The Solution: The Strategy Pattern

The Strategy Pattern solves this by moving each algorithm into its own separate class. Each "Strategy" class follows a common interface, typically defined via an Abstract Base Class (from lesson 23). The ShippingCalculator then holds a reference to one of these strategies and delegates the work to it.

from abc import ABC, abstractmethod

class ShippingStrategy(ABC):
    @abstractmethod
    def calculate(self, weight):
        pass

class GroundShipping(ShippingStrategy):
    def calculate(self, weight):
        return weight * 1.5

class DroneShipping(ShippingStrategy):
    def calculate(self, weight):
        return weight * 5.0

class ShippingCalculator:
    def __init__(self, strategy: ShippingStrategy):
        self.strategy = strategy

    def get_cost(self, weight):
        return self.strategy.calculate(weight)

# Runtime swapping
calc = ShippingCalculator(GroundShipping())
print(calc.get_cost(10))  # 15.0

calc.strategy = DroneShipping()
print(calc.get_cost(10))  # 50.0

Why This Works

By decoupling the "Context" (ShippingCalculator) from the "Algorithm" (ShippingStrategy), you gain several advantages:

  1. Runtime Flexibility: You can change the behavior of an object while the program is running, simply by swapping the strategy object.
  2. Simplified Testing: Each algorithm is isolated in its own class, making it significantly easier to unit test.
  3. Clean Code: Your core logic remains small and focused, as it doesn't need to know the implementation details of every possible variation.

Key Takeaway: The Strategy Pattern enables you to replace complex, conditional logic with interchangeable objects, making your systems more modular, testable, and adaptable to future requirements.