Skip to content
BBaskaran

Strategy

Define a family of interchangeable algorithms and choose one at runtime.

Use it when

You have several variants of an algorithm and want to switch between them cleanly.

/**
 * Strategy: let the customer pick a shipping option, and swap the cost rule.
 *
 * Real-world scenario: a checkout page offers Standard, Express and Store pickup.
 * Each option calculates shipping differently. Instead of an if/else on the
 * option inside the cart, each rule is its own strategy object, and the cart
 * just asks whichever one is selected. Adding "Next-day" is one new class.
 *
 * Tip: in TypeScript a strategy can also be a plain function, such as
 * (subtotal, weightKg) => number; classes are used here to make each role easy
 * to see.
 */

// Strategy: one way of calculating shipping.
interface ShippingStrategy {
  readonly name: string;
  cost(subtotal: number, weightKg: number): number;
}

// Concrete strategies: interchangeable rules. Each takes only the inputs it needs.
class Standard implements ShippingStrategy {
  readonly name = "Standard (5 days)";

  cost(subtotal: number): number {
    return subtotal >= 50 ? 0 : 4.99; // free over $50
  }
}

class Express implements ShippingStrategy {
  readonly name = "Express (next day)";

  cost(_subtotal: number, weightKg: number): number {
    return 9.99 + 2.0 * weightKg;
  }
}

class StorePickup implements ShippingStrategy {
  readonly name = "Store pickup";

  cost(): number {
    return 0;
  }
}

// Context: uses whichever strategy is selected, without knowing which one.
class Cart {
  readonly subtotal: number;
  readonly weightKg: number;
  shipping: ShippingStrategy = new Standard();

  constructor(subtotal: number, weightKg: number) {
    this.subtotal = subtotal;
    this.weightKg = weightKg;
  }

  total(): number {
    return this.subtotal + this.shipping.cost(this.subtotal, this.weightKg);
  }
}

function clientCode(): void {
  const cart = new Cart(42.0, 1.5);

  // The customer tries each option; the cart code never changes.
  for (const option of [new Standard(), new Express(), new StorePickup()]) {
    cart.shipping = option;
    console.log(`${option.name.padEnd(20)} total $${cart.total().toFixed(2)}`);
  }
}

clientCode();

// Output:
// Standard (5 days)    total $46.99
// Express (next day)   total $54.99
// Store pickup         total $42.00

How it works

RoleClassesWhat it does
StrategyShippingStrategyInterface: one way of calculating shipping cost
Concrete strategiesStandard, Express, StorePickupInterchangeable rules, each in its own class
ContextCartUses whichever strategy is selected, with no if/else on the option
ClientclientCode()Swaps the strategy at runtime, as a customer picking an option