Strategy
Also known as: Policy
Define a family of interchangeable algorithms and let you choose which one to use at runtime.
- 8 animated steps
- 6 languages
- Behavioral patterns
The problem
Shipping cost calculation varies: express, standard, in-store pickup, promoโฆ The shippingCost() method becomes a big switch that grows with every new offer.
The solution
Extract each algorithm into a class (or function) that follows the same interface. The context receives a strategy and delegates the calculation to it; you can swap it on the fly.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The client picks a strategy.
- Checkout โ ShippingCalculator: cost(2 kg)
- The context delegates the calculation, without knowing how it is done.
- ExpressStrategy โ ShippingCalculator: 15 DT
- The user chooses in-store pickup: the algorithm is swapped on the fly.
- Checkout โ ShippingCalculator: cost(2 kg)
- ShippingCalculator โ PickupStrategy: calculate(2)
- Same calling code, different result. New offer = new strategy.
An analogy
Getting to the airport: car, bus or taxi. The goal is the same, you pick the strategy based on budget and time.
When to use it
- Several variants of the same algorithm
- Pricing, sorting, compression, payment, authentication
- Getting rid of big switch statements on a type
Pros and cons
Pros
- Algorithms isolated and testable
- Swappable at runtime
- Open/Closed
Cons
- The client must know the available strategies
- Overkill if the algorithm rarely changes (a function is enough)
Implementations
The same example, written idiomatically in each language.
Strategy in Python
from typing import Callable
# In Python, a strategy can simply be a function
ShippingStrategy = Callable[[float], float]
def express(weight: float) -> float: return 10 + weight * 2.5
def standard(weight: float) -> float: return 5 + weight
def pickup(_: float) -> float: return 0.0
class ShippingCalculator:
def __init__(self, strategy: ShippingStrategy = standard):
self.strategy = strategy
def cost(self, weight: float) -> float:
return self.strategy(weight)
calc = ShippingCalculator(express)
print(calc.cost(2)) # 15.0
calc.strategy = pickup
print(calc.cost(2)) # 0.0
Strategy in TypeScript
interface ShippingStrategy {
calculate(weightKg: number): number;
}
const express: ShippingStrategy = { calculate: (w) => 10 + w * 2.5 };
const standard: ShippingStrategy = { calculate: (w) => 5 + w };
const pickup: ShippingStrategy = { calculate: () => 0 };
class ShippingCalculator {
constructor(private strategy: ShippingStrategy = standard) {}
setStrategy(s: ShippingStrategy) { this.strategy = s; }
cost(weightKg: number) { return this.strategy.calculate(weightKg); }
}
const calc = new ShippingCalculator(express);
calc.cost(2); // 15
calc.setStrategy(pickup);
calc.cost(2); // 0
Strategy in Java
@FunctionalInterface
interface ShippingStrategy { double calculate(double weightKg); }
class ShippingCalculator {
private ShippingStrategy strategy;
ShippingCalculator(ShippingStrategy s) { strategy = s; }
void setStrategy(ShippingStrategy s) { strategy = s; }
double cost(double w) { return strategy.calculate(w); }
}
ShippingStrategy express = w -> 10 + w * 2.5;
ShippingStrategy pickup = w -> 0;
var calc = new ShippingCalculator(express);
calc.cost(2); // 15.0
calc.setStrategy(pickup);
calc.cost(2); // 0.0
Strategy in C#
interface IShippingStrategy { decimal Calculate(decimal kg); }
class Express : IShippingStrategy { public decimal Calculate(decimal kg) => 10 + kg * 2.5m; }
class Standard : IShippingStrategy { public decimal Calculate(decimal kg) => 5 + kg; }
class Pickup : IShippingStrategy { public decimal Calculate(decimal kg) => 0; }
class ShippingCalculator(IShippingStrategy strategy)
{
public IShippingStrategy Strategy { get; set; } = strategy;
public decimal Cost(decimal kg) => Strategy.Calculate(kg);
}
var calc = new ShippingCalculator(new Express());
calc.Cost(2); // 15
calc.Strategy = new Pickup();
calc.Cost(2); // 0
Strategy in PHP
interface ShippingStrategy { public function calculate(float $kg): float; }
final class Express implements ShippingStrategy
{
public function calculate(float $kg): float { return 10 + $kg * 2.5; }
}
final class Pickup implements ShippingStrategy
{
public function calculate(float $kg): float { return 0; }
}
final class ShippingCalculator
{
public function __construct(private ShippingStrategy $strategy) {}
public function setStrategy(ShippingStrategy $s): void { $this->strategy = $s; }
public function cost(float $kg): float { return $this->strategy->calculate($kg); }
}
$calc = new ShippingCalculator(new Express());
echo $calc->cost(2); // 15
$calc->setStrategy(new Pickup());
echo $calc->cost(2); // 0
Strategy in Go
type ShippingStrategy func(weightKg float64) float64
var (
Express ShippingStrategy = func(w float64) float64 { return 10 + w*2.5 }
Standard ShippingStrategy = func(w float64) float64 { return 5 + w }
Pickup ShippingStrategy = func(float64) float64 { return 0 }
)
type ShippingCalculator struct {
Strategy ShippingStrategy
}
func (c *ShippingCalculator) Cost(w float64) float64 { return c.Strategy(w) }
calc := &ShippingCalculator{Strategy: Express}
fmt.Println(calc.Cost(2)) // 15
calc.Strategy = Pickup
fmt.Println(calc.Cost(2)) // 0
Frequently asked questions
What is the Strategy design pattern?
Define a family of interchangeable algorithms and let you choose which one to use at runtime. Extract each algorithm into a class (or function) that follows the same interface. The context receives a strategy and delegates the calculation to it; you can swap it on the fly.
When should you use the Strategy pattern?
Several variants of the same algorithm; Pricing, sorting, compression, payment, authentication; Getting rid of big switch statements on a type.
What are the pros and cons of the Strategy pattern?
Pros: Algorithms isolated and testable; Swappable at runtime; Open/Closed. Cons: The client must know the available strategies; Overkill if the algorithm rarely changes (a function is enough).