What is the Factory Pattern?

The Factory pattern uses a function (or method) to create objects, hiding the details of which concrete type is built and how it is configured; callers ask for "a notifier for email" and get a ready-to-use object.

Factory functions in JavaScript

In JavaScript a plain function that returns an object is a factory: no new, no classes needed. Closures inside it can hold private state.

Benefits

  • Encapsulated creation logic: validation, defaults and wiring live in one place.
  • Choose the implementation at runtime: based on configuration, environment or input (e.g. a storage adapter that uses IndexedDB in the browser and memory in tests).
  • Private state through closures without class syntax.
  • No this binding problems, because returned methods can close over variables instead of using this.
  • Easy to swap in tests.

Factory vs constructor/class

  • Classes give you instanceof, shared prototype methods (less memory per instance) and inheritance.
  • Factories give you flexibility, privacy via closures, and the ability to return different types or cached instances. Both are fine; pick based on whether you need those features.

Variations

  • Simple factory: a function with a switch or registry of types.
  • Factory method: subclasses decide which object to create.
  • Abstract factory: creates families of related objects (e.g. light and dark UI kits).
  • Registry-based factory: register new types without editing the factory (open/closed principle).

Code example

js
1// A registry-based factory: add new types without editing the factory
2const notifierTypes = new Map();
3const registerNotifier = (type, create) => notifierTypes.set(type, create);
4
5function createNotifier(type, options = {}) {
6 const create = notifierTypes.get(type);
7 if (!create) throw new Error(`Unknown notifier type: ${type}`);
8 return create({ retries: 3, ...options });
9}
10
11registerNotifier("email", ({ from, retries }) => ({
12 send: (to, msg) => `email from ${from} to ${to}: ${msg} (retries ${retries})`,
13}));
14registerNotifier("sms", ({ retries }) => ({
15 send: (to, msg) => `sms to ${to}: ${msg.slice(0, 160)} (retries ${retries})`,
16}));
17
18console.log(createNotifier("email", { from: "noreply@app.com" }).send("ada@x.com", "Welcome!"));
19console.log(createNotifier("sms").send("+44 7700 900000", "Your code is 1234"));
20
21try {
22 createNotifier("pigeon");
23} catch (e) {
24 console.log(e.message); // Unknown notifier type: pigeon
25}
26
27// Factory function with private state and no `this`
28function createCounter(start = 0) {
29 let count = start;
30 return { increment: () => ++count, reset: () => (count = start), get value() { return count; } };
31}
32const counter = createCounter(10);
33const { increment } = counter; // safe to destructure: no `this`
34increment();
35increment();
36console.log(counter.value); // 12

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app