Strategy Pattern — Design Patterns

Strategy puts each way of calculating (an algorithm) in its own function, called a strategy. Every strategy has the same shape (it takes a weight and returns…

Picture a screwdriver with bits you can change. It has one handle and several bits: cross, flat, star. Every bit fits into the same socket in the handle. You put in the bit that matches the screw, and the handle doesn't need to know which bit is in it. A new kind of screw only needs one new bit, and the handle doesn't change.

The Strategy pattern works the same way. Each way of calculating (an algorithm) goes in its own function, called a strategy, and every strategy has the same shape. The main code picks or receives one of them while the program runs, without knowing what's inside. In code, the handle is the main code that calculates the shipping cost, each bit is one strategy, and the shared socket is the shared shape: it takes a weight and returns a number.

The problem: a switch that keeps growing

In the first version, every rate lives in one function, and each new service adds one more case. In this code, case "express" forgot its break. The express rate is $18/kg. Take a guess first: what does calculateShipping("express", 2) give?

function calculateShipping(service, kg) {
  let price
  switch (service) {
    case "regular":
      price = kg * 10
      break
    case "express":
      price = kg * 18
      // break forgotten
    case "cargo":
      price = Math.max(kg, 10) * 6
      break
  }
  return price
}

console.log(calculateShipping("express", 2))   // 60
console.log(calculateShipping("overnight", 2)) // undefined

Without break, a switch keeps going into the next case. price is briefly 36, then overwritten by the cargo formula: Math.max(2, 10) * 6 = 60. The express customer pays $60, not $36. A service that doesn't exist isn't refused either: calculateShipping("overnight", 2) only returns undefined.

Every new service means opening the same function again, in the middle of formulas that already work.

The strategy: one function per way of calculating

In the Strategy version, each formula becomes one function in the PRICING object. calculateShipping only takes the function that matches, then calls it:

const PRICING = {
  regular: (kg) => kg * 10,
  express: (kg) => kg * 18,
  cargo: (kg) => Math.max(kg, 10) * 6,
  sameday: (kg) => kg * 25,
}

function calculateShipping(service, kg) {
  if (!Object.hasOwn(PRICING, service)) throw new Error("Unknown service")
  const strategy = PRICING[service]
  return strategy(kg)
}

console.log(calculateShipping("express", 2)) // 36

The results for a 2 kg parcel:

service the strategy picked calculateShipping(service, 2)
"regular" kg * 10 20
"express" kg * 18 36
"cargo" Math.max(kg, 10) * 6 60
"sameday" kg * 25 50

A strategy passed in from outside

A strategy doesn't have to be picked by a key. The strategy function itself can be passed as an argument. For example, Kancil Courier's monthly promo:

const PROMO = {
  none: (price) => price,
  discount10: (price) => price * 0.9,
  minus20: (price) => Math.max(price - 20, 0),
}

function checkout(service, kg, promo) {
  return promo(calculateShipping(service, kg))
}

console.log(checkout("express", 2, PROMO.discount10)) // 32.4
console.log(checkout("express", 2, PROMO.minus20))    // 16

checkout receives the promo as a function, then calls it with the shipping cost from calculateShipping. When the marketing team changes the promo, checkout isn't touched.

JavaScript itself uses this shape in array.sort(compareFn). The way to sort is already in sort, and the way to compare two values is what you pass, as a function. With no compare function, [25, 9, 18].sort() compares those numbers as text and gives [18, 25, 9]. With .sort((a, b) => a - b), it gives [9, 18, 25].

Strategy in the Behavioral group

Remember the three groups of patterns from the first lesson, What Is a Design Pattern?: Creational (how objects are made), Structural (how objects are put together and connected), and Behavioral (how objects tell each other things and share work). Strategy belongs to Behavioral: it decides which part does the calculation and which algorithm runs, not how objects are made or put together.

The smallest form of Strategy: const strategies = { add: (a, b) => a + b, multiply: (a, b) => a * b }. strategies["multiply"] takes the multiplying function, and strategies["multiply"](3, 4) gives 12.

The exercise: formatPrice

In the exercise, you use strategies to format a price. The starter already holds a formatters object with the keys de, us and compact, plus a formatPrice(amount, locale) function that's still empty:

When you don't need a strategy

⚠️ Keys, shapes and order that often go wrong

TL;DR: Strategy puts each way of calculating (an algorithm) in its own function, called a strategy. Every strategy has the same shape (it takes a weight and returns a number), so they can be swapped. The main code picks a strategy from an object by its key (PRICING[service](kg)) or receives it as an argument (checkout(service, kg, promo), array.sort(compareFn)). No growing switch and no forgotten break. In the switch version, a forgotten break turns the shipping cost for express 2 kg into 60, not 36. An unknown key is refused with throw new Error(...). Strategy is in the Behavioral group (how objects tell each other things and share work). When the ways of calculating only differ by a number, use a data table. When there's only one way, write it directly.

⚡ A switch with a forgotten break

Guess first: in the switch of the function calculateShipping(service, kg), express is kg * 18 and cargo is Math.max(kg, 10) * 6. case "express" forgot its break, and case "cargo" comes after it. What does calculateShipping("express", 2) give?

60, not 36. Without break, a switch keeps going into the next case, so the express price is overwritten by the cargo formula: Math.max(2, 10) * 6.

Meaning: When every rate lives in one switch, every new service means opening the same function again, in the middle of formulas that already work.

⚡ One function per way of calculating

Write:

const PRICING = {
  regular: (kg) => kg * 10,
  express: (kg) => kg * 18,
  cargo: (kg) => Math.max(kg, 10) * 6,
}

function calculateShipping(service, kg) {
  if (!Object.hasOwn(PRICING, service)) throw new Error("Unknown service")
  const strategy = PRICING[service]
  return strategy(kg)
}

Meaning: This is the Strategy pattern: each way of calculating the shipping cost is one function in the PRICING object, called a strategy. Every strategy has the same shape: it takes kg and returns a number. That is why strategies can be swapped. calculateShipping takes the strategy by its key, then calls it. There's no break to forget, and a new service is one line.

⚡ A strategy passed in from outside

Write:

console.log(checkout("express", 2, PROMO.discount10)) // 32.4

Meaning: checkout(service, kg, promo) calculates the shipping cost, then calls promo with that cost. PROMO.discount10 is a 10% discount strategy: the cost for express 2 kg, 36, becomes 32.4. So a strategy function can be passed straight in as an argument, like in array.sort(compareFn), which receives the way to compare two values. Strategy belongs to the Behavioral group: it decides which algorithm runs, not how objects are made or put together.

What you will learn