Programming Search⌘K

Patterncore

Strategy pattern

Also called Strategy, Policy, policy pattern.

A context object holds a strategy and calls it for one step of its work. The client chooses the strategy, so that step can change without a change to the context.

Family
behavioral-design
Intent
Put each variant of an algorithm behind one interface, so that the client can choose a variant and the code that uses the algorithm does not change.
Also called
Policy
Refactorings
Replace conditional logic with strategy

Intent

Put each variant of an algorithm behind one interface. The client chooses a variant and gives it to the code that uses the algorithm. That code calls the interface and does not change when a variant is added.1

Problem

A checkout computes the total of a cart. The shop has three prices. The regular price is the sum of the lines. A promotion takes ten percent off, and a bulk price takes 50 cents off each unit of a line with five or more units. Next month marketing will add another plan. The direct design puts all the plans in one function and selects one with a conditional:

def total(items, plan):
    if plan == "regular":
        return sum(price * quantity for _, price, quantity in items)
    if plan == "ten percent off":
        return total(items, "regular") * 90 // 100
    if plan == "bulk":
        return sum((price - 50 if quantity >= 5 else price) * quantity for _, price, quantity in items)
    raise ValueError(f"unknown plan: {plan}")


cart = [("book", 1500, 2), ("pen", 200, 5)]
for plan in ["regular", "ten percent off", "bulk"]:
    print(f"{plan}: {total(cart, plan)} cents")
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents

This works for three plans. Each added plan changes the function, so each change can break the plans that already work. A test of one plan must go through the same function as all the others. The code that owns the cart also owns every pricing rule, and a library cannot let its users add a plan.

The forces are these. The step that varies must change without a change to the code around it. The variants must be testable one at a time. The choice of a variant can come from configuration or from the user at run time. Kerievsky describes the starting point of the refactoring in the same terms. Conditional logic in a method controls which of several variants of a calculation runs.4

Solution

Move each variant into its own object or function with the same signature. This is the strategy. The checkout becomes the context. It holds a reference to one strategy and calls it for the step that varies. The client creates the strategy that it wants and gives it to the context.1

 Context (Checkout)                 Strategy (interface)
 -------------------------          ---------------------
 pricing: Strategy  ------------->  total(items) -> cents
 total(items):                                ^
   return pricing.total(items)                |
                               +--------------+--------------+
                               |              |              |
                           Regular      TenPercentOff       Bulk

The participants in Design Patterns are the Strategy interface, the concrete strategies, and the Context.1 The context depends only on the interface. The concrete strategies do not know the context. The client knows both, because it makes the choice.

There are two ways to give the strategy its data. The context can pass the data as arguments, as total(items) does here. Or the context can pass itself, and the strategy reads what it needs from the context. The first keeps the strategy independent of the context. The second gives the strategy access to more data, but it couples the strategy to the interface of the context.1

In a language with first-class functions, a strategy with one operation is a function. The interface is a function type, and each concrete strategy is a function value. Norvig counts Strategy among four patterns that first-class functions make simpler. He describes the dynamic form of Strategy as a variable whose value is a function.3 The standard libraries use this form everywhere:

Language Strategy as a value
Python the key function of sorted and list.sort5
Java java.util.Comparator, a functional interface, so a lambda or a method reference can be one89
C# the Comparison<T> delegate, given to List<T>.Sort10
Go the cmp function of slices.SortFunc11
Rust the closure of slice::sort_by12
C++ the Compare template parameter of std::sort14
JavaScript the comparator of Array.prototype.sort15
C the function pointer compar of qsort16
Kotlin a parameter of a function type such as (A, B) -> C17

The class form is still useful in two cases. The strategy can have more than one operation that must vary together, such as compress and decompress. Or it can have configuration that a reader should see as named fields.

Static and dynamic binding. A context can take the strategy as a value at run time, or as a type parameter at compile time. Design Patterns describes the second form with C++ templates: the strategy is fixed when the context is compiled, and the call needs no indirection.1 Rust generics with F: Fn(...) and C++ templates give this form. A Box<dyn Fn(...)> in Rust, a std::function in C++, and a trait object give the dynamic form, which can change while the program runs.13

Example

The example files show one program in each language. A cart has two books at 1500 cents and five pens at 200 cents. One checkout object computes the total with three strategies in turn: regular (4000), ten percent off (3600) and bulk (3750). Each language uses its own usual form:

Language Form
Python plain functions in an attribute of the context
JavaScript functions in an object field
TypeScript a function type alias
Java a functional interface with method references
Kotlin a function type and function references
C# a delegate type
Go a named func type
Rust a generic context with F: Fn, and a Box<dyn Fn> list
C a function pointer in a struct
C++ a std::function member, and a template for the static form
Bash the name of a function in a variable
PythonGitHub
from collections.abc import Callable
from dataclasses import dataclass


@dataclass(frozen=True)
class Item:
    name: str
    price: int  # in cents
    quantity: int


Pricing = Callable[[list[Item]], int]


def regular(items: list[Item]) -> int:
    return sum(item.price * item.quantity for item in items)


def ten_percent_off(items: list[Item]) -> int:
    return regular(items) * 90 // 100


def bulk(items: list[Item]) -> int:
    # 50 cents off each unit of a line with 5 or more units.
    return sum(
        (item.price - 50 if item.quantity >= 5 else item.price) * item.quantity
        for item in items
    )


class Checkout:
    def __init__(self, pricing: Pricing) -> None:
        self.pricing = pricing

    def total(self, items: list[Item]) -> int:
        return self.pricing(items)


cart = [Item("book", 1500, 2), Item("pen", 200, 5)]
checkout = Checkout(regular)
for name, pricing in [("regular", regular), ("ten percent off", ten_percent_off), ("bulk", bulk)]:
    checkout.pricing = pricing
    print(f"{name}: {checkout.total(cart)} cents")
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Python has no strategy construct. A function is a value, so each strategy is a plain function and the interface is the type alias Pricing.
  • The checkout changes its strategy at run time by assignment to checkout.pricing.
  • typing.Protocol with a __call__ method or with named methods is the class form, for a strategy with more than one operation.
  • The standard library uses the same form: sorted(items, key=...) takes the key function as a strategy.
#include <functional>
#include <iostream>
#include <span>
#include <string>
#include <utility>
#include <vector>

struct Item {
    std::string name;
    int price;  // in cents
    int quantity;
};

using Pricing = std::function<int(std::span<const Item>)>;

// The dynamic form: the strategy is a value, and it can change at run time.
class Checkout {
public:
    explicit Checkout(Pricing pricing) : pricing_(std::move(pricing)) {}
    void set_pricing(Pricing pricing) { pricing_ = std::move(pricing); }
    int total(std::span<const Item> items) const { return pricing_(items); }

private:
    Pricing pricing_;
};

// The static form: the strategy is a template parameter, fixed at compile time.
template <typename Strategy>
int total_with(Strategy strategy, std::span<const Item> items) {
    return strategy(items);
}

int regular(std::span<const Item> items) {
    int total = 0;
    for (const auto& item : items) {
        total += item.price * item.quantity;
    }
    return total;
}

int ten_percent_off(std::span<const Item> items) { return regular(items) * 90 / 100; }

// 50 cents off each unit of a line with 5 or more units.
int bulk(std::span<const Item> items) {
    int total = 0;
    for (const auto& item : items) {
        total += (item.quantity >= 5 ? item.price - 50 : item.price) * item.quantity;
    }
    return total;
}

int main() {
    const std::vector<Item> cart{{"book", 1500, 2}, {"pen", 200, 5}};
    const std::vector<std::pair<std::string, Pricing>> strategies{
        {"regular", regular},
        {"ten percent off", ten_percent_off},
        {"bulk", bulk},
    };
    Checkout checkout{regular};
    for (const auto& [name, pricing] : strategies) {
        checkout.set_pricing(pricing);
        std::cout << name << ": " << checkout.total(cart) << " cents\n";
    }
    std::cout << "static bulk: " << total_with(bulk, cart) << " cents\n";
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
static bulk: 3750 cents
  • Verdict: idiom. C++ has both forms. std::function holds any callable with the right signature, so the strategy can change at run time. A template parameter fixes it at compile time, as the Compare parameter of std::sort does.
  • The static form lets the compiler inline the call. Each strategy type makes its own copy of the template.
  • A strategy class with virtual functions is the class form, for a strategy with several operations. Lambdas cover the common case of one operation.
JavaGitHub
import java.util.List;

public class Main {
    record Item(String name, int price, int quantity) {}

    @FunctionalInterface
    interface Pricing {
        int total(List<Item> items);
    }

    static final class Checkout {
        private Pricing pricing;

        Checkout(Pricing pricing) {
            this.pricing = pricing;
        }

        void setPricing(Pricing pricing) {
            this.pricing = pricing;
        }

        int total(List<Item> items) {
            return pricing.total(items);
        }
    }

    static int regular(List<Item> items) {
        return items.stream().mapToInt(i -> i.price() * i.quantity()).sum();
    }

    static int tenPercentOff(List<Item> items) {
        return regular(items) * 90 / 100;
    }

    // 50 cents off each unit of a line with 5 or more units.
    static int bulk(List<Item> items) {
        return items.stream()
                .mapToInt(i -> (i.quantity() >= 5 ? i.price() - 50 : i.price()) * i.quantity())
                .sum();
    }

    record Named(String name, Pricing pricing) {}

    public static void main(String[] args) {
        List<Item> cart = List.of(new Item("book", 1500, 2), new Item("pen", 200, 5));
        List<Named> strategies = List.of(
                new Named("regular", Main::regular),
                new Named("ten percent off", Main::tenPercentOff),
                new Named("bulk", Main::bulk));
        Checkout checkout = new Checkout(Main::regular);
        for (Named s : strategies) {
            checkout.setPricing(s.pricing());
            System.out.println(s.name() + ": " + checkout.total(cart) + " cents");
        }
    }
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Pricing is a functional interface: it has one abstract method, so a lambda or a method reference such as Main::bulk is an instance of it.
  • @FunctionalInterface makes the compiler reject a second abstract method. It is optional.
  • java.util.function.ToIntFunction<List<Item>> would also work. A named interface gives the strategy a name in the type of the context and in stack traces.
  • java.util.Comparator is the strategy of the JDK for order. TreeMap, List.sort and Collections.sort take one.
#include <stddef.h>
#include <stdio.h>

struct item {
    const char *name;
    int price; /* in cents */
    int quantity;
};

typedef int (*pricing_fn)(const struct item *items, size_t count);

struct checkout {
    pricing_fn pricing;
};

static int checkout_total(const struct checkout *c, const struct item *items, size_t count) {
    return c->pricing(items, count);
}

static int regular(const struct item *items, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; i++) {
        total += items[i].price * items[i].quantity;
    }
    return total;
}

static int ten_percent_off(const struct item *items, size_t count) {
    return regular(items, count) * 90 / 100;
}

/* 50 cents off each unit of a line with 5 or more units. */
static int bulk(const struct item *items, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; i++) {
        int price = items[i].quantity >= 5 ? items[i].price - 50 : items[i].price;
        total += price * items[i].quantity;
    }
    return total;
}

int main(void) {
    const struct item cart[] = {{"book", 1500, 2}, {"pen", 200, 5}};
    const size_t count = sizeof cart / sizeof cart[0];
    const struct {
        const char *name;
        pricing_fn pricing;
    } strategies[] = {
        {"regular", regular},
        {"ten percent off", ten_percent_off},
        {"bulk", bulk},
    };
    struct checkout checkout = {regular};
    for (size_t i = 0; i < sizeof strategies / sizeof strategies[0]; i++) {
        checkout.pricing = strategies[i].pricing;
        printf("%s: %d cents\n", strategies[i].name, checkout_total(&checkout, cart, count));
    }
    return 0;
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. A function pointer in a struct is the strategy. qsort in the standard library takes its comparison as a function pointer in the same way.
  • C has no closures. So a strategy that needs configuration, such as the percent of a discount, needs a void * context argument next to the pointer.
  • The struct of function pointers is the class form. It is how C code builds a vtable by hand, for a strategy with several operations.
var cart = new List<Item> { new("book", 1500, 2), new("pen", 200, 5) };

Pricing regular = items => items.Sum(i => i.Price * i.Quantity);
Pricing tenPercentOff = items => regular(items) * 90 / 100;
// 50 cents off each unit of a line with 5 or more units.
Pricing bulk = items => items.Sum(i => (i.Quantity >= 5 ? i.Price - 50 : i.Price) * i.Quantity);

var checkout = new Checkout(regular);
foreach (var (name, pricing) in new (string, Pricing)[]
{
    ("regular", regular),
    ("ten percent off", tenPercentOff),
    ("bulk", bulk),
})
{
    checkout.Pricing = pricing;
    Console.WriteLine($"{name}: {checkout.Total(cart)} cents");
}

record Item(string Name, int Price, int Quantity);

delegate int Pricing(IReadOnlyList<Item> items);

class Checkout(Pricing pricing)
{
    public Pricing Pricing { get; set; } = pricing;

    public int Total(IReadOnlyList<Item> items) => Pricing(items);
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. A delegate type is the strategy interface, and a lambda is a strategy. The base library uses the same form in Comparison<T>, which List<T>.Sort takes.
  • Func<IReadOnlyList<Item>, int> would also work. A named delegate type such as Pricing documents the role and cannot be mixed up with another Func of the same shape.
  • The class Checkout uses a primary constructor. Its parameter initializes the property.
JavaScriptGitHub
const regular = (items) =>
  items.reduce((sum, item) => sum + item.price * item.quantity, 0);

const tenPercentOff = (items) => Math.trunc((regular(items) * 90) / 100);

// 50 cents off each unit of a line with 5 or more units.
const bulk = (items) =>
  items.reduce(
    (sum, item) =>
      sum + (item.quantity >= 5 ? item.price - 50 : item.price) * item.quantity,
    0,
  );

class Checkout {
  constructor(pricing) {
    this.pricing = pricing;
  }

  total(items) {
    return this.pricing(items);
  }
}

const cart = [
  { name: "book", price: 1500, quantity: 2 },
  { name: "pen", price: 200, quantity: 5 },
];
const checkout = new Checkout(regular);
for (const [name, pricing] of [
  ["regular", regular],
  ["ten percent off", tenPercentOff],
  ["bulk", bulk],
]) {
  checkout.pricing = pricing;
  console.log(`${name}: ${checkout.total(cart)} cents`);
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. JavaScript functions are values, so a strategy is a function in a field of the context.
  • this.pricing(items) calls the function as a method of the checkout, so this inside a function strategy would be the checkout. Arrow functions ignore that this.
  • Math.trunc keeps the integer cents. Numbers are doubles, so integer cents stay exact up to Number.MAX_SAFE_INTEGER.
  • Array.prototype.sort(comparator) takes its comparison as a strategy in the same way.
TypeScriptGitHub
interface Item {
  readonly name: string;
  readonly price: number; // in cents
  readonly quantity: number;
}

type Pricing = (items: readonly Item[]) => number;

const regular: Pricing = (items) =>
  items.reduce((sum, item) => sum + item.price * item.quantity, 0);

const tenPercentOff: Pricing = (items) => Math.trunc((regular(items) * 90) / 100);

// 50 cents off each unit of a line with 5 or more units.
const bulk: Pricing = (items) =>
  items.reduce(
    (sum, item) =>
      sum + (item.quantity >= 5 ? item.price - 50 : item.price) * item.quantity,
    0,
  );

class Checkout {
  pricing: Pricing;

  constructor(pricing: Pricing) {
    this.pricing = pricing;
  }

  total(items: readonly Item[]): number {
    return this.pricing(items);
  }
}

const cart: Item[] = [
  { name: "book", price: 1500, quantity: 2 },
  { name: "pen", price: 200, quantity: 5 },
];
const strategies: [string, Pricing][] = [
  ["regular", regular],
  ["ten percent off", tenPercentOff],
  ["bulk", bulk],
];
const checkout = new Checkout(regular);
for (const [name, pricing] of strategies) {
  checkout.pricing = pricing;
  console.log(`${name}: ${checkout.total(cart)} cents`);
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. The strategy interface is a function type alias, and each strategy is a function value that the compiler checks against it.
  • Type compatibility is structural, so any function with a compatible signature is a Pricing. It needs no implements clause.
  • The class declares its field and assigns it in the constructor. A parameter property such as constructor(public pricing: Pricing) is shorter, but it makes JavaScript code, so Node.js cannot run it by type stripping alone.
package main

import "fmt"

type Item struct {
	Name     string
	Price    int // in cents
	Quantity int
}

// Pricing is the strategy: any function with this signature.
type Pricing func(items []Item) int

type Checkout struct {
	Pricing Pricing
}

func (c *Checkout) Total(items []Item) int {
	return c.Pricing(items)
}

func regular(items []Item) int {
	total := 0
	for _, item := range items {
		total += item.Price * item.Quantity
	}
	return total
}

func tenPercentOff(items []Item) int {
	return regular(items) * 90 / 100
}

// bulk takes 50 cents off each unit of a line with 5 or more units.
func bulk(items []Item) int {
	total := 0
	for _, item := range items {
		price := item.Price
		if item.Quantity >= 5 {
			price -= 50
		}
		total += price * item.Quantity
	}
	return total
}

func main() {
	cart := []Item{{"book", 1500, 2}, {"pen", 200, 5}}
	strategies := []struct {
		name    string
		pricing Pricing
	}{
		{"regular", regular},
		{"ten percent off", tenPercentOff},
		{"bulk", bulk},
	}
	checkout := &Checkout{Pricing: regular}
	for _, s := range strategies {
		checkout.Pricing = s.pricing
		fmt.Printf("%s: %d cents\n", s.name, checkout.Total(cart))
	}
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Go functions are values, so a named func type is the strategy interface. slices.SortFunc and sort.Slice take their comparison in the same way.
  • A one-method interface such as type Pricer interface { Total([]Item) int } is the class form. A func type can satisfy it through a method, as http.HandlerFunc satisfies http.Handler.
  • A nil Pricing field makes Total panic. A constructor that requires the strategy, or a default in Total, prevents this.
RustGitHub
struct Item {
    price: u32, // in cents
    quantity: u32,
}

// The static form: the strategy is a type parameter, fixed at compile time.
struct Checkout<F: Fn(&[Item]) -> u32> {
    pricing: F,
}

impl<F: Fn(&[Item]) -> u32> Checkout<F> {
    fn total(&self, items: &[Item]) -> u32 {
        (self.pricing)(items)
    }
}

fn regular(items: &[Item]) -> u32 {
    items.iter().map(|i| i.price * i.quantity).sum()
}

fn ten_percent_off(items: &[Item]) -> u32 {
    regular(items) * 90 / 100
}

// 50 cents off each unit of a line with 5 or more units.
fn bulk(items: &[Item]) -> u32 {
    items
        .iter()
        .map(|i| {
            let price = if i.quantity >= 5 { i.price - 50 } else { i.price };
            price * i.quantity
        })
        .sum()
}

fn main() {
    let cart = [
        Item { price: 1500, quantity: 2 },
        Item { price: 200, quantity: 5 },
    ];

    // The dynamic form: trait objects in a list, chosen at run time.
    let strategies: Vec<(&str, Box<dyn Fn(&[Item]) -> u32>)> = vec![
        ("regular", Box::new(regular)),
        ("ten percent off", Box::new(ten_percent_off)),
        ("bulk", Box::new(bulk)),
    ];
    for (name, pricing) in &strategies {
        let checkout = Checkout { pricing: |items: &[Item]| pricing(items) };
        println!("{name}: {} cents", checkout.total(&cart));
    }
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Rust has closures and function items, and the Fn traits are the strategy interface.
  • Checkout<F> is the static form. The compiler makes one copy of Checkout for each strategy type and can inline the call. The type of the checkout fixes its strategy, so it cannot change at run time.
  • Box<dyn Fn(&[Item]) -> u32> is the dynamic form. Values of different closure types share one type, so they fit in one Vec, at the cost of a call through a vtable.
  • (self.pricing)(items) needs the parentheses. Without them, Rust looks for a method named pricing.
KotlinGitHub
data class Item(val name: String, val price: Int, val quantity: Int)

typealias Pricing = (List<Item>) -> Int

class Checkout(var pricing: Pricing) {
    fun total(items: List<Item>): Int = pricing(items)
}

fun regular(items: List<Item>): Int = items.sumOf { it.price * it.quantity }

fun tenPercentOff(items: List<Item>): Int = regular(items) * 90 / 100

// 50 cents off each unit of a line with 5 or more units.
fun bulk(items: List<Item>): Int =
    items.sumOf { (if (it.quantity >= 5) it.price - 50 else it.price) * it.quantity }

fun main() {
    val cart = listOf(Item("book", 1500, 2), Item("pen", 200, 5))
    val strategies: List<Pair<String, Pricing>> = listOf(
        "regular" to ::regular,
        "ten percent off" to ::tenPercentOff,
        "bulk" to ::bulk,
    )
    val checkout = Checkout(::regular)
    for ((name, pricing) in strategies) {
        checkout.pricing = pricing
        println("$name: ${checkout.total(cart)} cents")
    }
}
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Kotlin has function types, so the strategy interface is (List<Item>) -> Int and ::bulk is a reference to a top-level function of that type.
  • typealias only names the function type. It does not make a type of its own.
  • A fun interface gives the class form a single abstract method, so a lambda can still be passed where it is expected.
BashGitHub
# Each line of the cart: name price-in-cents quantity.
cart=("book 1500 2" "pen 200 5")

regular() {
    local total=0 name price quantity
    for line in "${cart[@]}"; do
        read -r name price quantity <<<"$line"
        total=$((total + price * quantity))
    done
    echo "$total"
}

ten_percent_off() {
    echo $(($(regular) * 90 / 100))
}

# 50 cents off each unit of a line with 5 or more units.
bulk() {
    local total=0 name price quantity
    for line in "${cart[@]}"; do
        read -r name price quantity <<<"$line"
        if ((quantity >= 5)); then
            price=$((price - 50))
        fi
        total=$((total + price * quantity))
    done
    echo "$total"
}

# The context holds the name of the strategy function.
pricing=regular
checkout_total() {
    "$pricing"
}

for strategy in regular ten_percent_off bulk; do
    pricing=$strategy
    echo "${strategy//_/ }: $(checkout_total) cents"
done
Output
regular: 4000 cents
ten percent off: 3600 cents
bulk: 3750 cents
  • Verdict: idiom. Bash functions are not values, but a variable can hold the name of a function, and "$pricing" calls it.
  • A function returns its result on standard output, so $(checkout_total) runs it in a subshell.
  • The cart is a global array, because Bash cannot pass an array to a function by value. A name reference (local -n) is the other choice.
  • The name in the variable is not checked before the call. An unknown name fails with "command not found" at run time.

Consequences

Design Patterns lists these benefits.1 The strategies form a family of related algorithms, and code they share can move into a common base or a helper. A strategy is an alternative to a subclass of the context. The context does not need one subclass for each algorithm, so the algorithm and the rest of the context vary on their own. The conditional that selected a variant goes away from the context. The client can choose between implementations with the same result and different costs in time or in space.

The same chapter lists these costs.1 The client must know the strategies to choose one, so the knowledge of the variants moves to the client and does not disappear. The interface between the context and the strategy must pass every piece of data that any strategy needs. So a small strategy gets arguments that it ignores. The program has more objects. A strategy with no state can be shared by many contexts, which keeps the number of objects small.

The conditional moves; it does not vanish. Some code must still turn a configuration value into a strategy. Put this choice in one place, at the edge of the program, often as a map from a name to a function. The rest of the program then gets a strategy and never asks which one it is.

A stateful strategy must not be shared. A strategy that keeps state between calls works for one context only. In this program one discount object serves two customers. The first customer uses up the state, and the second customer loses a discount that is his:

This code runs but gives a wrong answer on purpose.

def regular(items):
    return sum(price * quantity for _, price, quantity in items)


class FirstOrderDiscount:
    def __init__(self):
        self.used = False

    def __call__(self, items):
        if self.used:
            return regular(items)
        self.used = True
        return regular(items) * 90 // 100


cart = [("book", 1500, 2), ("pen", 200, 5)]
first_order = FirstOrderDiscount()
for customer in ["ana", "ben"]:
    print(f"{customer}: {first_order(cart)} cents")
Output
ana: 3600 cents
ben: 4000 cents

The fact "this is the first order" belongs to the customer, not to the pricing rule. Move it into the data that the context passes, and the strategy has no state again. The interface grows by one argument, which is the communication cost above:

def regular(items, orders_before):
    return sum(price * quantity for _, price, quantity in items)


def first_order_discount(items, orders_before):
    total = regular(items, orders_before)
    return total * 90 // 100 if orders_before == 0 else total


cart = [("book", 1500, 2), ("pen", 200, 5)]
history = {"ana": 0, "ben": 0, "cy": 3}
for customer, orders_before in history.items():
    print(f"{customer}: {first_order_discount(cart, orders_before)} cents")
Output
ana: 3600 cents
ben: 3600 cents
cy: 4000 cents

Closures made in a loop. When strategies are functions, a program often makes them in a loop. A closure in Python captures the variable, not its value at the time of creation. Every function made in the loop below reads percent when it runs, after the loop has ended:6

This code runs but gives a wrong answer on purpose.

def regular(items):
    return sum(price * quantity for _, price, quantity in items)


strategies = {}
for percent in [10, 20]:
    strategies[f"{percent} percent off"] = lambda items: regular(items) * (100 - percent) // 100

cart = [("book", 1500, 2), ("pen", 200, 5)]
for name, pricing in strategies.items():
    print(f"{name}: {pricing(cart)} cents")
Output
10 percent off: 3200 cents
20 percent off: 3200 cents

The FAQ of Python gives the fix: bind the value when the function is made, with a default argument such as lambda items, p=percent: .... functools.partial does the same and keeps the argument out of the signature that callers see:67

from functools import partial


def regular(items):
    return sum(price * quantity for _, price, quantity in items)


def percent_off(percent, items):
    return regular(items) * (100 - percent) // 100


strategies = {}
for percent in [10, 20]:
    strategies[f"{percent} percent off"] = partial(percent_off, percent)

cart = [("book", 1500, 2), ("pen", 200, 5)]
for name, pricing in strategies.items():
    print(f"{name}: {pricing(cart)} cents")
Output
10 percent off: 3600 cents
20 percent off: 3200 cents

A JavaScript for loop that declares its variable with let makes a fresh copy of the binding for each pass. So the same loop in JavaScript gives the expected values.22 A loop with var has the Python behaviour, because a var binding belongs to the whole function.

When not to use it

Do not use the pattern for an algorithm that has one form, or for variants that never change after the program is written. A conditional with two or three branches in one place is easier to read than an interface, three classes and a factory. Move to strategies when a second place starts to switch on the same value, or when the variants need separate tests.

Do not use the class form where the language has function values. A one-method interface with one class for each variant adds names and files and gives no benefit over a function. Keep the class form for a strategy with several operations or with named configuration.

Do not use a strategy to vary a small step inside a larger fixed algorithm when only subclasses will ever supply it. Template Method does that with a hook method. Design Patterns states the difference: template methods use inheritance to vary part of an algorithm, and strategies use delegation to vary the entire algorithm.2 If the variants must change at run time or combine with other choices, prefer the strategy.

A program that has a strategy for each small decision becomes hard to follow. The reader of the context cannot see which code runs, and must find where the client made its choice.

Template Method. Both patterns fix the structure and let a part vary. Template Method varies a step with an overridden method, chosen when the subclass is written. Strategy varies the algorithm with a delegated object, chosen when the context is built or later.2

State. State has the same structure as Strategy: a context that delegates to an object behind an interface. The difference is who changes the object. In State, the context or the state objects choose the next state as the context moves between states.21 In Strategy, the client chooses, and the strategy does not replace itself.

Factory Method and Abstract Factory. A creation step is also an algorithm, so a function that returns a product is a strategy for creation. The Factory Method pattern varies that step by subclassing. Passing a factory function to the context, the strategy form, varies it by delegation.

Decorator. Design Patterns contrasts the two: a decorator changes the skin of an object, and a strategy changes its guts.20 A decorator wraps an object and keeps its interface. A strategy is a part inside the context.

Flyweight. Strategies with no state can be shared between contexts, as flyweights.1

Dependency injection. Passing a strategy to a constructor is constructor injection, in the terms of Fowler.23 A container that injects an implementation of an interface into a service makes the choice of a strategy part of the configuration of the program.

Higher-order functions. A function that takes a function argument, such as map, filter or sort, is the context of a strategy in the functional style. Norvig's slide on Strategy makes this point: with first-class functions the pattern is invisible.3

Known uses

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Strategy (Intent, Also Known As, Motivation, Participants, Consequences, Implementation, Related Patterns)
  2. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Template Method (Related Patterns)
  3. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 9 and slide 10 (16 of 23 patterns simpler; first-class functions make Command, Strategy, Template-Method and Visitor simpler), slide 16 (Dynamic Pattern, Strategy)
  4. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 7, Simplification, Replace Conditional Logic with Strategy (problem and solution)
  5. Sorting Techniques, Python 3.14 documentation, Key Functions
  6. Programming FAQ, Python 3.14 documentation, Why do lambdas defined in a loop with different values all return the same result?
  7. The Python Standard Library, functools, Python 3.14, functools.partial
  8. Java SE 25 API, java.util.Comparator, interface description (functional interface)
  9. The Java Language Specification, Java SE 25 Edition, 9.8 Functional Interfaces
  10. .NET API reference, System.Comparison<T>, delegate description
  11. Go standard library, package slices, func SortFunc
  12. Rust standard library, primitive slice, method sort_by
  13. The Rust Programming Language, chapter 18.2, Using Trait Objects to Abstract over Shared Behavior (trait objects and dynamic dispatch)
  14. Working Draft, Programming Languages, C++ (N4950), [alg.sort] (the Compare template parameter of sort)
  15. ECMAScript Language Specification (draft), 23.1.3.30 Array.prototype.sort (comparator)
  16. ISO/IEC 9899:2024 (C23) working draft N3220, 7.24.5.2 The qsort function, paragraphs 1 to 4
  17. Kotlin documentation, Higher-order functions and lambdas, Function types
  18. OpenJDK jdk-25+36 source, java/util/TreeMap.java, getEntryUsingComparator, lines 403 to 419
  19. Go go1.27.3 source, src/slices/sort.go, SortFunc, lines 30 to 33
  20. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Decorator (Implementation, changing the skin of an object versus changing its guts)
  21. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, State (Implementation, who defines the state transitions)
  22. ECMAScript Language Specification (draft), 14.7.4.4 CreatePerIterationEnvironment
  23. Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern, January 2004, Forms of Dependency Injection; Constructor Injection with PicoContainer

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4ZB5QG/text.yaml