Strategy

Put each variant of an algorithm in its own class behind one interface, so callers can swap behaviour without changing their code.

Description

Strategy turns a family of interchangeable algorithms, such as pricing rules, payment methods or export formats, into separate objects that share one interface. The code that uses them, the context, only knows the interface.

Instead of a growing if/else or switch that picks behaviour, the context is handed a strategy and calls it. A new variant is a new class; the context and the other variants stay untouched. This is the Open/Closed principle in its most practical form.

Class diagram

usesCheckout- strategy: ShippingStrategy+ setShipping(s): void+ total(order): number«interface»ShippingStrategy+ cost(order): numberStandardShipping+ cost(order): numberExpressShipping+ cost(order): numberFreeOverThreshold- fallback: ShippingStrategy+ cost(order): number

Strategy pattern class diagram

  1. Class Checkout with + setShipping(s): void, + total(order): number.
  2. Interface ShippingStrategy with + cost(order): number.
  3. Class StandardShipping with + cost(order): number.
  4. Class ExpressShipping with + cost(order): number.
  5. Class FreeOverThreshold with + cost(order): number.
  6. Checkout uses ShippingStrategy.
  7. StandardShipping implements ShippingStrategy.
  8. ExpressShipping implements ShippingStrategy.
  9. FreeOverThreshold implements ShippingStrategy.

Sequence diagram

ClientCheckoutStandardShippingExpressShipping1. total(order)2. cost(order)3. 6.104. 48.105. setShipping(express)6. total(order)7. cost(order)8. 15.209. 57.20

Strategy pattern sequence diagram

  1. Client → Checkout: total(order).
  2. Checkout → StandardShipping: cost(order).
  3. Checkout receives "6.10" back from StandardShipping.
  4. Client receives "48.10" back from Checkout.
  5. Client → Checkout: setShipping(express).
  6. Client → Checkout: total(order).
  7. Checkout → ExpressShipping: cost(order).
  8. Checkout receives "15.20" back from ExpressShipping.
  9. Client receives "57.20" back from Checkout.

TypeScript example

A checkout that calculates shipping with a swappable strategy. Adding a new shipping option means adding one class; Checkout never changes.

strategy.ts
// Strategy: checkout picks a shipping-cost algorithm at runtime.

interface Order {
  subtotal: number;
  weightKg: number;
}

// The strategy interface: one method, one job.
interface ShippingStrategy {
  readonly name: string;
  cost(order: Order): number;
}

// Concrete strategies. Adding a new one never touches Checkout.
class StandardShipping implements ShippingStrategy {
  readonly name = "Standard";
  cost(order: Order): number {
    return 4.9 + order.weightKg * 0.4;
  }
}

class ExpressShipping implements ShippingStrategy {
  readonly name = "Express";
  cost(order: Order): number {
    return 12.5 + order.weightKg * 0.9;
  }
}

class FreeOverThreshold implements ShippingStrategy {
  readonly name = "Free over 50";
  private readonly fallback: ShippingStrategy;
  constructor(fallback: ShippingStrategy) {
    this.fallback = fallback;
  }
  cost(order: Order): number {
    return order.subtotal >= 50 ? 0 : this.fallback.cost(order);
  }
}

// The context: works with any strategy through the interface.
class Checkout {
  private strategy: ShippingStrategy;
  constructor(strategy: ShippingStrategy) {
    this.strategy = strategy;
  }
  setShipping(strategy: ShippingStrategy): void {
    this.strategy = strategy;
  }
  total(order: Order): number {
    return round(order.subtotal + this.strategy.cost(order));
  }
}

const round = (n: number) => Math.round(n * 100) / 100;

export function demo(): string[] {
  const order: Order = { subtotal: 42, weightKg: 3 };
  const checkout = new Checkout(new StandardShipping());
  const lines = [`Standard: ${checkout.total(order)}`];

  checkout.setShipping(new ExpressShipping()); // swap behaviour at runtime
  lines.push(`Express: ${checkout.total(order)}`);

  checkout.setShipping(new FreeOverThreshold(new StandardShipping()));
  lines.push(`Free over 50: ${checkout.total({ ...order, subtotal: 60 })}`);
  return lines;
}

When to use it

Use it when

  • You have several ways to do the same job and choose between them by configuration, customer, region or feature flag.
  • A conditional that selects behaviour keeps growing, and every change risks breaking the other branches.
  • You want to test each variant on its own, with no setup for the others.
  • The behaviour must change at runtime, for example when a user picks a shipping option.

Avoid it when

  • There are only two simple variants that rarely change. An if is clearer.
  • The variants differ by a value, not by logic. Pass a parameter instead.
  • Your language makes functions first-class and the strategy has one method. A plain function type is the lighter version of the same idea.

Pitfalls

  • Callers must know which strategy to pick. Hide that choice in one place (a factory or a lookup table) instead of spreading it around.
  • Strategies that need very different inputs force a bloated interface. Group them differently, or pass a small context object.
  • Many tiny classes for trivial rules add ceremony without benefit. Start with functions; promote to classes when they need state or dependencies.
  • Strategies that secretly depend on each other or on shared mutable state defeat the point of swapping them.

Alternatives

Plain functions

Choose it when each variant is a single stateless computation. type ShippingCost = (o: Order) => number is a strategy without classes.

State

Choose it when the object should switch behaviour by itself as its internal state changes, instead of a caller choosing.

Template Method

Choose it when the steps of the algorithm are fixed and only a few steps vary; subclasses override those steps.

Decorator

Choose it when you want to add behaviour around an existing algorithm rather than replace it.