Thuta Learning
JavaScript
AdvancedProgrammingBeginner

Design Patterns

JavaScriptLesson 3230 min

What you'll walk away with

  • Explain a design pattern as a named solution to a recurring problem, not code to copy
  • Write a Module pattern with private state using an IIFE and a closure
  • Explain how a Singleton guarantees one instance, and what risks it brings
  • Choose between Strategy, Factory and Observer for a given problem

Explain it simply

Explain it simply

Architects do not invent a staircase from scratch for every house. They have named shapes, such as a spiral staircase or an L-shaped one, and pick one to fit the space and the need. Design patterns are the programmer's version: proven, named ways to solve a particular kind of problem.

Knowing the names speeds up conversations in a team: say "let's use a Strategy here" and everyone pictures the shape before a line is written. But a pattern is a tool, not a goal.

Problem → Why → Solution

The problem: every new shipping method means editing checkout

An online shop's checkout function calculates shipping with a chain of if/else branches. To add a new "same-day" option, you must open the working checkout() and squeeze another branch in among the pricing and discount code. None of the methods can be tested on its own either.

checkout.js
function checkout(subtotal, weightKg, method) {
  let shipping;
  if (method === "standard") {
    shipping = 5 + weightKg * 1.5;
  } else if (method === "express") {
    shipping = 15 + weightKg * 2.5;
  } else if (method === "pickup") {
    shipping = 0;
  } // every new method = another edit to this function
  // ...discounts, tax and receipts also live here...
  return subtotal + shipping;
}

Why is this a problem?

checkout() mixes the part that keeps changing, how shipping is priced, with the stable part, how an order is completed. The Strategy pattern pulls each pricing rule out into its own function, and checkout simply calls the chosen one. Adding a method becomes adding one entry to an object.

Core concept: isolate the part that changes

A design pattern is a named shape of solution for a recurring design problem, not exact code to copy and paste. Most patterns share one core idea: separate the part that changes often from the part that stays stable, and put a clear interface between them. Many patterns were first written down for class-based languages like Java, but in JavaScript, where functions are values and closures exist, most of them become shorter and simpler.

PatternProblem it solvesTypical JavaScript shape
ModuleHide state, expose only a public APIIIFE + closure, or an ES module
SingletonExactly one shared instanceCreate on first call, then cache it
FactoryObject creation is complex or variesA createX(options) function
StrategySwap an algorithm at run timeAn object or Map of functions
ObserverNotify many parties of an eventA listener list with on() / emit()

The Module pattern relies on closures: variables are declared inside an IIFE, a function that runs immediately, and an object of the methods you want to expose is returned. Today every ES module file already has its own scope and is evaluated only once, so the IIFE is no longer needed, but you will meet this shape constantly in older code and libraries. A Singleton creates its instance the first time it is needed and returns that same instance on every later call. An Observer keeps a list of listeners that want to hear about an event, and the emitter calls them without knowing who they are.

Every pattern has an abstraction cost: more files, more names, more layers of indirection. Before reaching for one, ask whether this spot really has variation. If there is only one shipping method, a plain function beats a Strategy.

Mental model: how to pick a pattern
  1. Find what actually varies
  2. Move that part into a function/object
  3. Stable code calls only the interface
  4. Check: would a plain function do?

The problem comes first; the pattern follows it.

General pattern

javascript
// Module: private state + public API
const Service = (function () {
  let privateState = initialValue;
  return { publicMethod() { /* uses privateState */ } };
})();

// Singleton: build once, reuse forever
let instance;
function getInstance() {
  return instance ?? (instance = createInstance());
}

The Module pattern runs an IIFE immediately and hands out only the returned object. The Singleton caches the instance in a variable and creates it only when it does not exist yet.

Example: a Calculator module and a Database singleton

Calculator hides result inside a closure, and every method returns this so calls can be chained as .add().add().subtract(). Database's getInstance() is called twice, yet notice that "Creating the connection" is printed only once.

patterns.js
// 1. Module pattern: an IIFE hides state and returns a public API
const Calculator = (function () {
  let result = 0; // private

  return {
    add(n) {
      result += n;
      return this; // returning the object enables chaining
    },
    subtract(n) {
      result -= n;
      return this;
    },
    getResult() {
      return result;
    },
    reset() {
      result = 0;
      return this;
    },
  };
})();

Calculator.add(10).add(5).subtract(3);
console.log(`Result: ${Calculator.getResult()}`);
console.log(`After reset: ${Calculator.reset().add(2).getResult()}`);

// 2. Singleton pattern: create the instance once, lazily
const Database = (function () {
  let instance;

  function createInstance() {
    console.log("Creating the connection (runs once)");
    return { connection: "MySQL Connection" };
  }

  return {
    getInstance() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    },
  };
})();

const db1 = Database.getInstance();
const db2 = Database.getInstance();
console.log(db1 === db2); // true (same instance)

Code breakdown

  1. Lines 2-3let result = 0; // private

    Declared inside the IIFE, result is visible only to the four methods; Calculator.result is undefined.

  2. Line 8return this; // returning the object enables chaining

    Called as Calculator.add(10), this is the Calculator object, and returning it lets you chain .add(5). Written as an arrow function, the method would get the wrong this and chaining would break.

  3. Line 22})();

    The trailing () runs the function immediately. What Calculator receives is not the function but the object it returns.

  4. Lines 39-41if (!instance) {

    createInstance() runs only while instance is empty. On the second call this block is skipped and the stored object is returned. This is called lazy initialisation.

  5. Line 49console.log(db1 === db2); // true (same instance)

    === compares objects by reference, so true proves db1 and db2 point at the very same object.

You should see
Result: 12
After reset: 2
Creating the connection (runs once)
true

The Strategy pattern: swappable shipping rules

Let's rewrite the checkout from the problem section with the Strategy pattern. Each shipping rule is a function in an object, and checkout just looks one up by name and calls it. Adding "same-day" means adding one line to shippingStrategies without touching checkout, and each rule can be tested on its own as shippingStrategies.express(2).

shipping-strategy.js
const shippingStrategies = {
  standard: (weightKg) => 5 + weightKg * 1.5,
  express: (weightKg) => 15 + weightKg * 2.5,
  pickup: () => 0,
};

function checkout(subtotal, weightKg, method) {
  const strategy = shippingStrategies[method];
  if (!strategy) throw new Error(`Unknown shipping method: ${method}`);
  const total = subtotal + strategy(weightKg);
  return `${method}: ${total.toFixed(2)}`;
}

console.log(checkout(40, 2, "standard")); // standard: 48.00
console.log(checkout(40, 2, "express"));  // express: 60.00
console.log(checkout(40, 2, "pickup"));   // pickup: 40.00

The Factory pattern: creation rules in one place

If user objects are built by hand as { name, role, permissions } in ten places, changing an admin's permissions means editing all ten. A factory function gathers the creation rules in one place: callers say what they want and never need to know how it is assembled.

user-factory.js
const PERMISSIONS = {
  admin: ["read", "write", "delete"],
  editor: ["read", "write"],
  viewer: ["read"],
};

function createUser(name, role = "viewer") {
  const permissions = PERMISSIONS[role];
  if (!permissions) throw new Error(`Unknown role: ${role}`);
  return { name, role, permissions: [...permissions] };
}

console.log(createUser("Su", "admin").permissions.join(",")); // read,write,delete
console.log(createUser("Ko Ko").role);                       // viewer

In real projects

Where this shows up in real projects

You meet these patterns everywhere, often unnamed. The browser's addEventListener and Node.js's EventEmitter are the Observer pattern, and the subscribe() of state libraries such as Redux follows it too. Authentication libraries like Passport.js literally call each login method (Google, GitHub, password) a "strategy", and passing a comparison function to Array's sort() is itself a Strategy.

Database connection pools, loggers and app configuration are usually exported from an ES module so the whole application shares one instance; since a module is evaluated only once, that is effectively a Singleton. To swap a real database for a fake in tests, teams use factory functions such as createDb(config). Knowing the patterns also means that when you read library documentation, you immediately understand why it was designed that way.

Common mistakes

Common mistakes

1. Using a pattern because it has a name

Adding Factory or Strategy layers where nothing varies only makes the code longer and harder to read. After adding a pattern, check whether changes or tests really became easier; if not, go back to a plain function.

2. Treating a Singleton as hidden global state

Mutable data inside a Singleton leaks from one test into the next, so tests fail when their order changes. Keep Singletons for resources such as connections and pass state around as parameters.

3. Writing chainable methods as arrow functions

With add: (n) => { result += n; return this; }, the arrow function has no this of its own, so this is not Calculator (in a module it is undefined) and Calculator.add(1).add(2) throws a TypeError. Write chainable methods in the add(n) { ... } form.

4. Never removing Observer listeners

If a component is destroyed but its listener stays registered, memory is never freed and the emitter keeps calling something that no longer exists. Make on() return an unsubscribe function and call it when you are done.

Mini challenge

Mini challenge: build an Observer event emitter

Write a createEmitter() factory for broadcasting order events. It must let listeners subscribe, unsubscribe and receive events.

  • on(event, handler) registers a listener and returns an unsubscribe function
  • emit(event, data) calls every listener of that event with data and returns how many were called
  • Emitting an event with no listeners returns 0 instead of throwing
  • Keep the listener list hidden inside a closure
emitter.js
function createEmitter() {
  // TODO: a private Map from event name to a Set of handlers

  return {
    on(event, handler) {
      // TODO: add handler; return a function that removes it
    },
    emit(event, data) {
      // TODO: call each handler with data; return how many ran (0 if none)
    },
  };
}

// TODO: subscribe an "email" and a "stock" listener to "placed"
// TODO: emit "placed", unsubscribe email, emit again, emit "cancelled"

Expected: After unsubscribing, the email listener must no longer run: Email: order #101 confirmed Stock: reserve 2 item(s) notified 2 listeners Stock: reserve 1 item(s) notified 1 listeners notified 0 listeners

Show hint

listeners.get(event) gives you a Set, and set.delete(handler) removes a handler. Returning () => listeners.get(event).delete(handler) from on() lets a closure remember both event and handler.

Show solution
emitter.js
function createEmitter() {
  const listeners = new Map(); // event name -> Set of handlers

  return {
    on(event, handler) {
      if (!listeners.has(event)) listeners.set(event, new Set());
      listeners.get(event).add(handler);
      return () => listeners.get(event).delete(handler);
    },
    emit(event, data) {
      const handlers = listeners.get(event);
      if (!handlers) return 0;
      for (const handler of handlers) handler(data);
      return handlers.size;
    },
  };
}

const orders = createEmitter();
const stopEmail = orders.on("placed", (o) => {
  console.log(`Email: order #${o.id} confirmed`);
});
orders.on("placed", (o) => console.log(`Stock: reserve ${o.qty} item(s)`));

console.log(`notified ${orders.emit("placed", { id: 101, qty: 2 })} listeners`);
stopEmail();
console.log(`notified ${orders.emit("placed", { id: 102, qty: 1 })} listeners`);
console.log(`notified ${orders.emit("cancelled", { id: 101 })} listeners`);

Quick quiz 1 / 3

Using the example's Calculator, after Calculator.add(10); what does console.log(Calculator.result) print?

Quick quiz 2 / 3

Users pick standard, express or pickup shipping, and more methods will be added later. Which pattern fits best?

Quick quiz 3 / 3

If a shopping cart lives inside a Singleton, what problem is most likely to show up in tests?

What to remember

  • A design pattern is a named solution shape for a recurring problem that isolates the part that changes.
  • The Module pattern hides state with a closure; a Singleton lazily creates exactly one instance.
  • Strategy makes algorithms swappable; Observer decouples an emitter from its listeners.
  • Every pattern costs abstraction, so use one only where real variation exists; otherwise prefer a plain function.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.