Abstract Factory Pattern — Design Patterns

An Abstract Factory makes a family of objects that must match each other: the label (tracking number), the tracker (how to look up the status) and the rate of…

The factory from the last lesson makes one object from one service name. A parcel passed to a partner courier needs more than that: a tracking sticker, a way to track it, and a rate table. All three have to come from the same partner.

An Abstract Factory is one object that makes a family of objects, which means several objects that have to match each other. The caller picks the family once, and every part then comes from that same family, so they can't be mixed. Picture Kancil Courier working with two partner couriers, Merpati and Jalak. Each partner gives you one document folder with their tracking stickers, their way of tracking a parcel, and their rate table. You take one folder, and everything in it matches. If the contents of two folders get mixed, for example a Merpati sticker tracked in Jalak's system, the parcel will never be found. In code, the folder is the abstract factory (later called a kit), and the things inside the folder are the objects it makes.

The problem: each part picked on its own

A parcel passed to a partner needs three things: a label (the tracking number in the partner's format), a tracker (how to look up its status) and a pricer (the rate the partner bills). When every file picks its own partner, sooner or later one file uses a different partner. In this code, checkout.js still uses Merpati, while tracking.js and billing.js already use Jalak:

// checkout.js: the label is still Merpati
const label = merpatiLabel(42, 2.5)      // { trackingNo: "MTR-0042", kg: 2.5 }

// tracking.js: already switched to Jalak
console.log(jalakTracker().track(label.trackingNo))
// Jalak: MTR-0042 not recognised

// billing.js: Jalak too
console.log(jalakPricer().price(label.kg))
// 20, while Merpati bills 27

The customer can't track the parcel, and Kancil Courier charges $20 for a parcel the partner bills at $27. A loss of $7 per parcel, without a single error.

The abstract factory: one kit per partner

In the abstract factory version, each partner has one kit: one object with maker methods for the label, the tracker and the pricer. The code picks a kit once, then makes every part from that kit:

const PARTNERS = {
  merpati: {
    createLabel: (n, kg) => ({ trackingNo: "MTR-" + String(n).padStart(4, "0"), kg }),
    createTracker: () => ({
      track: (trackingNo) => trackingNo.startsWith("MTR-") ? "Merpati: " + trackingNo + " transit" : "Merpati: " + trackingNo + " not recognised",
    }),
    createPricer: () => ({ price: (kg) => Math.ceil(kg) * 9 }),
  },
  jalak: {
    createLabel: (n, kg) => ({ trackingNo: "JLK" + String(n).padStart(6, "0"), kg }),
    createTracker: () => ({
      track: (trackingNo) => trackingNo.startsWith("JLK") ? "Jalak: " + trackingNo + " transit" : "Jalak: " + trackingNo + " not recognised",
    }),
    createPricer: () => ({ price: (kg) => Math.max(kg, 1) * 8 }),
  },
}

function partnerKit(name) {
  if (!Object.hasOwn(PARTNERS, name)) throw new Error("Unknown partner")
  return PARTNERS[name]
}

const kit = partnerKit("merpati") // the only place a partner is picked
const label = kit.createLabel(42, 2.5)
console.log(label.trackingNo)                           // MTR-0042
console.log(kit.createTracker().track(label.trackingNo)) // Merpati: MTR-0042 transit
console.log(kit.createPricer().price(label.kg))         // 27

The result for parcel number 42 weighing 2.5 kg:

partnerKit("merpati") partnerKit("jalak")
trackingNo MTR-0042 JLK000042
track(trackingNo) Merpati: MTR-0042 transit Jalak: JLK000042 transit
price(2.5) Math.ceil(2.5) * 9 = 27 Math.max(2.5, 1) * 8 = 20

To move to Jalak, just change partnerKit("merpati") to partnerKit("jalak"): 1 line. All three parts move together.

A plain factory vs an abstract factory

Another common example: light and dark UI themes (the look of an app). Each theme has the components (parts of the display) Button, Input and Card. One factory per theme makes sure no dark Button sits next to a light Input in the same form.

In the exercise, you use that form. createThemeFactory(theme) returns an object { createButton, createInput }:

"light" "dark"
createButton(label) { kind: "button", label, bg: "#fff", color: "#000" } { kind: "button", label, bg: "#000", color: "#fff" }
createInput(placeholder) { kind: "input", placeholder, bg: "#fff", border: "#ccc" } { kind: "input", placeholder, bg: "#111", border: "#444" }

Any other theme must be refused right away with throw new Error("Unknown theme"), before any component is made.

When you don't need an abstract factory

⚠️ How do the families get mixed again?

TL;DR: An Abstract Factory makes a family of objects that must match each other: the label (tracking number), the tracker (how to look up the status) and the rate of the same partner courier, or the Button and Input of the same display theme. Every family has maker methods with the same names. The code picks the family once (partnerKit("merpati"), createThemeFactory("dark")) and then only uses the kit it picked (an object with the maker methods of that family), so parts from two families can't be mixed. Switching families is 1 line. The difference from a plain factory: a factory makes one kind of product (object), an abstract factory makes a family of products. The cost: a new product has to be written in every family. An unknown family name is refused with throw, for example throw new Error("Unknown theme").

⚡ Parts picked one by one

Write:

// tracking.js: already switched to Jalak
console.log(jalakTracker().track(label.trackingNo))
// Jalak: MTR-0042 not recognised
Guess first: Merpati and Jalak are two partner couriers. The label (tracking number) of this 2.5 kg parcel is made the Merpati way, but the customer's bill uses Jalak's rate. Merpati bills Kancil Courier $27, and Jalak's rate gives $20. How much is lost per parcel, and is there an error?

$7 per parcel, without a single error: Kancil Courier bills the customer $20, while Merpati bills $27.

Meaning: A parcel passed to a partner courier needs three parts: a label (the tracking number in the partner's format), a tracker (how to look up its status) and a pricer (the rate the partner bills). All three have to come from the same partner. In this code, a Merpati tracking number is looked up at Jalak, so it isn't recognised. When every file picks its partner on its own, sooner or later one file uses a different partner.

⚡ One kit per partner

Write:

const kit = partnerKit("merpati") // the only place a partner is picked
const label = kit.createLabel(42, 2.5)
console.log(label.trackingNo)                           // MTR-0042
console.log(kit.createTracker().track(label.trackingNo)) // Merpati: MTR-0042 transit
console.log(kit.createPricer().price(label.kg))         // 27

Meaning: An Abstract Factory makes a family of objects that must match each other. Here partnerKit("merpati") returns Merpati's kit: one object with maker methods for the label, the tracker and the pricer. Every partner's kit has methods with the same names, and the code picks the kit only once, so parts from two partners can't be mixed. Moving to Jalak means changing partnerKit("merpati") to partnerKit("jalak"): 1 line.

⚡ One product vs a family of products

Meaning: A plain factory (a simple factory) makes one kind of product, which means one kind of object: createShipment always makes a shipment object. An Abstract Factory makes a family of products that match each other, like the label, tracker and pricer of one partner. The cost: a new product, say createInsurance (the insurance maker), has to be written in every family.

What you will learn