Factory Pattern — Design Patterns

The Factory pattern hides the details of making an object in one function, called a factory. The factory picks the kind of object while the program runs, from…

The checkout page, the admin page and the Kancil Courier API (the door that other programs, such as online shops, use to place orders) all make shipment objects. When a new service arrives, how many files do you have to open? If every file writes its own if to pick the service, the answer is: all of them.

The Factory pattern puts object creation in one function, called a factory. That function picks the kind of object from the data it's given. So its callers (the code that calls it) only name the kind, without knowing how it's made. It's like ordering at a print shop: you just say "business cards, 100 copies", and the print shop knows the paper size, the paper type and the price. You don't need to memorise the price list. In code, you are the caller, the print shop is the factory, your order is data like "express" and the parcel's weight, and the printed cards are the object that is made.

The problem: an if copied into every caller

Kancil Courier makes shipment objects in three places: the checkout page (the payment page), the admin page, and the API for online shops. Each place writes its own if branch per service:

// checkout.js (admin.js and api.js have the same copy)
let shipment
if (service === "regular") {
  shipment = { service: "regular", kg, price: kg * 10, eta: "3 days" }
} else if (service === "express") {
  shipment = { service: "express", kg, price: kg * 18, eta: "1 day" }
}

When the cargo service is added, three files have to change. Forget one, and shipment in that file is never filled in for cargo orders, so it is undefined. As soon as its price is read, the cargo order stops with TypeError: Cannot read properties of undefined (reading 'price').

A factory function: one place that makes objects

A factory puts all those branches in one function, createShipment, and here it also adds the cargo service:

function createShipment(service, kg) {
  let shipment

  if (service === "regular") {
    shipment = { service: "regular", kg, price: kg * 10, eta: "3 days" }
  } else if (service === "express") {
    shipment = { service: "express", kg, price: kg * 18, eta: "1 day" }
  } else if (service === "cargo") {
    shipment = { service: "cargo", kg, price: Math.max(kg, 10) * 6, eta: "5 days" }
  } else {
    throw new Error("Unknown service")
  }

  shipment.describe = function () {
    return this.service + " " + this.kg + " kg: $" + this.price
  }

  return shipment
}

console.log(createShipment("express", 2).describe()) // express 2 kg: $36
console.log(createShipment("cargo", 4).describe())   // cargo 4 kg: $60

In the exercise, you use the same form for flat shapes. createShape(type, size) makes a circle, a square or a triangle, each with its area formula, plus describe(). For the circle, the area is rounded with toFixed(2): (Math.PI * 5 * 5).toFixed(2) gives the text "78.54", with two digits after the point.

The lookup version: one entry per service

The if chain still has to change for every new service. The lookup version (looking the kind up in a table) is shorter: how to make each kind is kept in one object, then picked by its key:

const SERVICES = {
  regular: (kg) => ({ service: "regular", kg, price: kg * 10, eta: "3 days" }),
  express: (kg) => ({ service: "express", kg, price: kg * 18, eta: "1 day" }),
  cargo: (kg) => ({ service: "cargo", kg, price: Math.max(kg, 10) * 6, eta: "5 days" }),
  sameday: (kg) => ({ service: "sameday", kg, price: kg * 25, eta: "today" }), // new
}

function createShipment(service, kg) {
  if (!Object.hasOwn(SERVICES, service)) throw new Error("Unknown service")
  return SERVICES[service](kg)
}

Two kinds of factory. createShipment above is a simple factory: one function that picks the kind of object from data. The Gang of Four book has another kind, Factory Method. In this kind, a parent class calls a maker method, and a subclass (a class that inherits from the parent class through extends) decides which object is made:

class Checkout {
  createShipment(kg) {
    return { service: "regular", kg, price: kg * 10 }
  }
  order(kg) {
    const s = this.createShipment(kg)
    return s.service + " " + s.kg + " kg: " + s.price
  }
}

class CargoCheckout extends Checkout {
  createShipment(kg) {
    return { service: "cargo", kg, price: Math.max(kg, 10) * 6 }
  }
}

console.log(new Checkout().order(2))      // regular 2 kg: 20
console.log(new CargoCheckout().order(4)) // cargo 4 kg: 60

order is written once, in Checkout. CargoCheckout inherits it through extends, and overrides only createShipment, which means it writes that method again with its own body. So order in CargoCheckout uses the cargo version of createShipment. Pick a simple factory when the kind is chosen from data, such as the service picked in a form: this is the most common kind in JavaScript. Pick Factory Method when the steps are the same for every kind and are already written in the parent class, and each subclass only changes the object that is made.

When you don't need a factory

⚠️ What makes a factory quietly wrong

TL;DR: The Factory pattern hides the details of making an object in one function, called a factory. The factory picks the kind of object while the program runs, from the data it's given. In Kancil Courier, createShipment(service, kg) makes shipment objects, with one if branch per service, each with its own price formula. That factory also adds a describe() method (written with function, so this is the object), and refuses unknown kinds with throw new Error(...). The lookup version (looking the kind up in a table) keeps how to make each kind as an entry in the object SERVICES, then calls SERVICES[service](kg): a new service is one line, and the code that calls it doesn't change. Check with Object.hasOwn that the key was really written in SERVICES. With only one kind, a factory isn't needed yet.

⚡ One place that makes objects

Write:

function createShipment(service, kg) {
  let shipment

  if (service === "regular") {
    shipment = { service: "regular", kg, price: kg * 10, eta: "3 days" }
  } else if (service === "express") {
    shipment = { service: "express", kg, price: kg * 18, eta: "1 day" }
  } else {
    throw new Error("Unknown service")
  }

  return shipment
}

Meaning: This is a factory: one function that makes shipment objects. A factory hides the details of making an object (each service's price and estimated time), and picks the kind while the program runs, from data such as the service picked in a form. The checkout page, the admin page and the API just write createShipment(service, kg).

⚡ Refuse unknown kinds

Guess first: why must a factory throw for a kind it doesn't know, instead of staying quiet?

Without throw, a service name with a typo makes the factory return undefined, which only causes an error far away. With throw new Error("Unknown service"), the caller finds out right away.

Meaning: If the factory also adds a describe method to the objects it makes, write describe with function () { ... }, not an arrow function, so this is the object that was made.

⚡ The lookup version: one line per service

Write:

function createShipment(service, kg) {
  if (!Object.hasOwn(SERVICES, service)) throw new Error("Unknown service")
  return SERVICES[service](kg)
}
Guess first: SERVICES is an object with one maker function per service. A sameday service is added to SERVICES. How many calling files (checkout, admin, API) have to change?

0 files. Checkout, admin and the API only call createShipment(service, kg), so they don't change at all.

Meaning: SERVICES[service] takes the maker function for that service, and (kg) calls it right away. Before that, Object.hasOwn checks the key was really written in SERVICES. So "toString", which every object inherits, can't pass as a service. With only one kind, a factory isn't needed yet.

What you will learn