Skip to content
01 / StrategyBehavioral12 minTypeScript

Change the shipping rule. Keep the checkout.

Use the Strategy pattern to switch between standard shipping, express delivery, and pickup without changing checkout logic.

Jump to the working demo

Start with the real-world problem

An online store adds express delivery and store pickup. The checkout already validates the basket, and every new delivery option adds another branch to the same function. A pricing change now risks breaking unrelated checkout behavior.

Before the pattern

A growing if/else chain mixes order validation with every delivery calculation. The same rules soon appear in the cart, checkout, and support dashboard.

What Strategy changes

Put interchangeable calculations behind one contract. The checkout owns validation and delegates the price calculation to the selected strategy. Changing the strategy changes the behavior, while the caller still invokes quote(order).

Context

ShippingCheckout

Validates the order and calls the currently selected strategy.

Contract

ShippingStrategy

Every implementation returns a shipping price in integer cents.

Implementations

Standard · Express · Pickup

Each class owns one pricing policy and can be replaced independently.

  1. 01

    Agree on the input and output

    Order contains a subtotal in cents and a package weight in kilograms. All strategies return cents, so checkout never needs to understand provider-specific units.

  2. 02

    Move the variation out

    Standard charges $4 plus $1 per started kilogram, with free delivery from $50. Express charges $10 plus $2 per started kilogram. Pickup is free. These are fictional teaching rules, not carrier quotes.

  3. 03

    Select at the boundary

    The UI selects a strategy; ShippingCheckout receives it. With a $35 basket weighing 2 kg, standard costs $6 and express costs $14. Switching to pickup returns $0 without editing the context.

Try it in the workbench

Live · runs in your browser

Result

Run the $35 / 2 kg basket, then switch from Standard to Express. The checkout stays the same; the pricing behavior changes.

The complete implementation

Download this self-contained example. With Node.js installed, run npx tsx strategy.ts in the download directory. The first run may install the TypeScript runner. No API credentials or other project files are needed.

strategy.ts
Download
export type Order = { subtotalCents: number; weightKg: number }

export interface ShippingStrategy {
  readonly name: string
  quote(order: Order): number
}

export class StandardShipping implements ShippingStrategy {
  readonly name = 'Standard'
  quote(order: Order) {
    return order.subtotalCents >= 5000 ? 0 : 400 + Math.ceil(order.weightKg) * 100
  }
}

export class ExpressShipping implements ShippingStrategy {
  readonly name = 'Express'
  quote(order: Order) {
    return 1000 + Math.ceil(order.weightKg) * 200
  }
}

export class StorePickup implements ShippingStrategy {
  readonly name = 'Pickup'
  quote() { return 0 }
}

export class ShippingCheckout {
  private strategy: ShippingStrategy
  constructor(strategy: ShippingStrategy) { this.strategy = strategy }
  setStrategy(strategy: ShippingStrategy) { this.strategy = strategy }

  quote(order: Order) {
    if (!Number.isSafeInteger(order.subtotalCents) || order.subtotalCents < 0) {
      throw new Error('Subtotal must be a non-negative integer in cents.')
    }
    if (!Number.isFinite(order.weightKg) || order.weightKg <= 0 || order.weightKg > 20) {
      throw new Error('Package weight must be greater than 0 and at most 20 kg.')
    }
    return this.strategy.quote(order)
  }
}

// Run this example with: npx tsx strategy.ts
const checkout = new ShippingCheckout(new StandardShipping())
const order = { subtotalCents: 3500, weightKg: 2 }
console.log(checkout.quote(order)) // 600
checkout.setStrategy(new ExpressShipping())
console.log(checkout.quote(order)) // 1400
checkout.setStrategy(new StorePickup())
console.log(checkout.quote(order)) // 0

Expected terminal output

600
1400
0

Make the tradeoff deliberately

A good fit

  • Several algorithms solve the same problem with the same input and output.
  • You need to select a policy at runtime or test it independently.

Keep it simpler when

  • There is one stable rule and no meaningful variation.
  • A small function parameter would express the variation more clearly than a class hierarchy.

Taking this into a real system

Keep money in integer minor units and define rounding explicitly. These policies share the same validation boundary and support packages up to 20 kg. A real integration also needs currency, destination, taxes, carrier availability, and timeout handling. Strategy organizes a choice; it does not implement those concerns for you.

Your turn

Make one small extension

Add an Economy strategy: $3 base plus $0.50 per started kilogram. What should a 2.2 kg package cost?

Show the reasoning

$4.50, or 450 cents: 300 + Math.ceil(2.2) * 50. Implement ShippingStrategy and pass it to ShippingCheckout; the checkout class should not change.

Further reading

Examples are original teaching implementations. Reference links provide language and API context; they are not claims that a provider uses this exact implementation.