Strategy
Encapsulating interchangeable algorithms behind a common interface — replacing conditionals, choosing strategies at runtime, strategies as functions, and real-world uses like comparators and pricing rules.
Intent: define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
It's the most-used behavioural pattern, and the clearest example of "favour composition over inheritance": the context has a strategy instead of being one.
From conditionals to strategies
double price(Cart cart, String mode) {
if (mode.equals("regular")) {
return cart.subtotal();
} else if (mode.equals("blackfriday")) {
return cart.subtotal() * 0.7;
} else if (mode.equals("member")) {
return cart.subtotal() * 0.9
- (cart.items() > 5 ? 10 : 0);
}
throw new IllegalArgumentException();
}Every new promotion edits (and risks breaking) this method.
interface PricingStrategy {
double price(Cart cart);
}
class Regular implements PricingStrategy {
public double price(Cart c) {
return c.subtotal();
}
}
class BlackFriday implements PricingStrategy {
public double price(Cart c) {
return c.subtotal() * 0.7;
}
}Each algorithm is separate, testable, and new ones don't touch existing code.
Full example
interface PricingStrategy { double price(Cart cart); }
class Regular implements PricingStrategy {
public double price(Cart c) { return c.subtotal(); }
}
class PercentOff implements PricingStrategy {
private final double pct;
PercentOff(double pct) { this.pct = pct; }
public double price(Cart c) { return c.subtotal() * (1 - pct / 100); }
}
class BuyXGetOneFree implements PricingStrategy {
private final int x;
BuyXGetOneFree(int x) { this.x = x; }
public double price(Cart c) {
int free = c.items() / (x + 1);
return c.subtotal() - free * c.cheapestItemPrice();
}
}
class Checkout {
private PricingStrategy pricing;
Checkout(PricingStrategy pricing) { this.pricing = pricing; }
void setPricing(PricingStrategy p) { this.pricing = p; } // swap at runtime
double total(Cart cart) { return pricing.price(cart) + shipping(cart); }
}
// Strategies are often just lambdas: PricingStrategy is a functional interface
Checkout checkout = new Checkout(c -> c.subtotal() * 0.8);from typing import Callable
# In Python, a strategy is usually just a function
PricingStrategy = Callable[[Cart], float]
def regular(cart: Cart) -> float:
return cart.subtotal
def percent_off(pct: float) -> PricingStrategy: # parameterised strategy
return lambda cart: cart.subtotal * (1 - pct / 100)
def buy_x_get_one_free(x: int) -> PricingStrategy:
def price(cart: Cart) -> float:
free = cart.items // (x + 1)
return cart.subtotal - free * cart.cheapest_item_price
return price
class Checkout:
def __init__(self, pricing: PricingStrategy = regular):
self.pricing = pricing
def total(self, cart: Cart) -> float:
return self.pricing(cart) + shipping(cart)
STRATEGIES = {"regular": regular, "summer": percent_off(20), "bogo": buy_x_get_one_free(1)}
checkout = Checkout(STRATEGIES[config.promo])type PricingStrategy = (cart: Cart) => number;
const regular: PricingStrategy = (c) => c.subtotal;
const percentOff = (pct: number): PricingStrategy => (c) => c.subtotal * (1 - pct / 100);
const buyXGetOneFree = (x: number): PricingStrategy => (c) =>
c.subtotal - Math.floor(c.items / (x + 1)) * c.cheapestItemPrice;
class Checkout {
constructor(private pricing: PricingStrategy = regular) {}
setPricing(p: PricingStrategy) { this.pricing = p; }
total(cart: Cart) { return this.pricing(cart) + shipping(cart); }
}
const strategies: Record<string, PricingStrategy> = {
regular, summer: percentOff(20), bogo: buyXGetOneFree(1),
};Strategies everywhere
| Where | Strategy |
|---|---|
| Sorting | Comparator / key= function passed to sort |
| Compression | Deflater levels, gzip vs brotli vs zstd |
| Auth | Passport.js strategies (local, Google, GitHub) |
| Retries | Backoff policy objects (fixed, exponential, jittered) |
| Load balancing | Round robin, least connections, consistent hash |
| Caching | Eviction policy (LRU, LFU, FIFO) |
| Validation | Pluggable validators per field |
| Routing / maps | Shortest vs fastest vs no-tolls path |
Choosing the strategy
Something must pick the strategy: configuration, a factory/registry keyed by name, user choice, or rules (feature flags, A/B tests). Keep that selection logic in one place, separate from the algorithms.
- Several variants of an algorithm, selected at runtime.
- A method with a growing
if/elseorswitchon a "mode" or "type". - You want to test each algorithm in isolation.
- Not worth it for two trivial branches that will never grow.
- Strategy encapsulates interchangeable algorithms behind one interface.
- It replaces conditionals with polymorphism (open/closed principle).
- In modern languages, a strategy is often just a function or lambda.
- Keep strategy selection (factory, config) separate from the strategies.
QStrategy vs State: what's the difference?medium
Both delegate to an interchangeable object. In Strategy, the client chooses the algorithm and strategies are independent and unaware of each other. In State, the object's behaviour changes as its internal state changes, and state objects typically trigger transitions to other states themselves.