Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Py

Python

Readable, batteries-included, and the default language of AI.

Paradigm
Multi-paradigm, OOP, functional
Typing
Dynamic, strong, optional type hints
Memory
Reference counting + cycle GC
Runs
CPython bytecode interpreter
Concurrency
asyncio, threads (GIL), multiprocessing
Behavioral pattern

Strategy

Intent

Defines a family of algorithms, puts each in its own class, and makes them interchangeable.

Problem

Shipping cost logic for ground, air and express sits in one growing switch statement.

Solution

Extract each algorithm into a strategy with a common interface. The context holds one and delegates. In languages with first-class functions, a strategy can be a function.

Real-world analogy

Think of it like this

Getting to the airport: bus, taxi or bike. Same goal, choose by budget and time.

Structure

association / extends implements / depends on
Context - strategy: Strategy+ setStrategy(s)+ doSomething() 14 «interface» Strategy + execute(data) 2 ConcreteStrategies + execute(data) 3 Client 5

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Context — Context keeps a reference to one strategy and talks to it only through the interface.
  2. 2Strategy — Strategy declares the interface common to every algorithm variant.
  3. 3ConcreteStrategies — Concrete Strategies implement the variations of the algorithm.
  4. 4Context — Each time the context runs the algorithm, it calls execute() on its current strategy.
  5. 5Client — Client creates a strategy and passes it to the context, and can swap it at runtime.

Try it

InteractiveSwitch the strategy and change the weight. The Order (context) code never changes.
Warehouse Customer
Strategy

Code example

strategy.py
from collections.abc import Callable

ShippingStrategy = Callable[[float], float]

def ground(kg: float) -> float:
    return 5 + kg * 1.2

def air(kg: float) -> float:
    return 15 + kg * 3

class Order:
    def __init__(self, strategy: ShippingStrategy) -> None:
        self.strategy = strategy

    def shipping(self, kg: float) -> float:
        return self.strategy(kg)

Order(air).shipping(2)   # 21.0

Applicability

Use Strategy when different variants of an algorithm, switchable at runtime.

Use Strategy when many similar classes differing only in behaviour.

Use Strategy when isolating business logic from algorithm details.

How to implement

  1. Identify the algorithm that varies
  2. Declare the strategy interface (or function type)
  3. Extract each algorithm into a strategy
  4. Give the context a strategy field and a setter
  5. Clients choose and inject the strategy

Pros and cons

Pros

  • Swap algorithms at runtime
  • Isolates algorithm details
  • Composition over inheritance
  • Open–Closed

Cons

  • Overkill for two stable algorithms
  • Clients must know the differences between strategies

Relations with other patterns

Check yourself

Check yourself

Checkout must calculate tax with a different algorithm per country, chosen at runtime.

Saved in this browser only. Part of Behavioral patterns (0/11), Hands-on: patterns with live demos (0/5).