Design Patterns

Pattern 20 of 23, Behavioral family

Strategy

Also known as: Policy

Define a family of interchangeable algorithms and let you choose which one to use at runtime.

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
  1. The client picks a strategy.
  2. Checkout โ†’ ShippingCalculator: cost(2 kg)
  3. The context delegates the calculation, without knowing how it is done.
  4. ExpressStrategy โ†’ ShippingCalculator: 15 DT
  5. The user chooses in-store pickup: the algorithm is swapped on the fly.
  6. Checkout โ†’ ShippingCalculator: cost(2 kg)
  7. ShippingCalculator โ†’ PickupStrategy: calculate(2)
  8. 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

strategy.py 23 lines
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

strategy.ts 20 lines
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

strategy.java 20 lines
@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#

strategy.cs 17 lines
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

strategy.php 25 lines
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

strategy.go 18 lines
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).