Tutorials JavaScript Design Patterns
Ch 62 / 78
Chapter 62 Advanced 22 min read JavaScript

JavaScript Design Patterns

Design patterns are reusable, battle-tested solutions to recurring software design problems. Mastering them turns you from someone who writes working code into someone who writes maintainable, scalable, and communicable code.

What you'll learn
The three pattern categories: Creational, Structural, Behavioural
Singleton — one instance, globally shared
Factory — create objects without specifying the class
Observer — event-driven pub/sub communication
Module — encapsulate private state with closures
Strategy, Decorator & Proxy patterns explained

What Are Design Patterns?

First formalised in the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software (the "Gang of Four" book), design patterns are named, documented solutions to problems that keep appearing in software development. They are not libraries, frameworks, or copy-paste code — they are concepts and templates you adapt to your specific context.

JavaScript patterns fall into three classic GoF categories:

Creational
Deal with object creation — how objects are created, composed, and represented, abstracting the instantiation process.
Creational
Structural
Deal with object composition — how classes and objects combine to form larger structures.
Structural
Behavioural
Deal with communication between objects — how responsibilities are distributed and how objects collaborate.
Behavioural
Pattern Category Core idea Real-world JS use
Singleton Creational Ensure a class has only one instance App config, DB connection, store
Factory Creational Delegate object creation to a factory function UI components, HTTP clients, loggers
Module Structural Encapsulate private state using closures / IIFE ES Modules, revealing module, namespacing
Decorator Structural Wrap an object to add behaviour without subclassing Middleware, HOFs, class decorators (TypeScript)
Proxy Structural Intercept and control access to another object Validation, caching, logging, ES6 Proxy
Observer Behavioural Notify dependents when an object's state changes Event emitters, reactive stores, pub/sub
Strategy Behavioural Define a family of algorithms, swap them at runtime Sort strategies, payment methods, validators

Singleton Pattern Creational

The Singleton guarantees that only one instance of a class or object exists across the entire application, and provides a global access point to it.

When to use: Global configuration object, database connection pool, application-level event bus, or any resource that must be shared and initialised only once.
JavaScript — Singleton (Closure)
const AppConfig = (() => {
  let instance;            // private — lives inside closure

  function createInstance() {
    return {
      theme : "dark",
      lang  : "en",
      apiUrl: "https://api.example.com",
    };
  }

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

// Always returns the same object
const cfg1 = AppConfig.getInstance();
const cfg2 = AppConfig.getInstance();
console.log(cfg1 === cfg2);   // true ✓
JavaScript — Singleton (ES6 Class)
class Store {
  static #instance = null;   // private static field (ES2022)

  constructor() {
    if (Store.#instance) return Store.#instance;
    this.state  = {};
    Store.#instance = this;
  }

  set(key, value) { this.state[key] = value; }
  get(key)        { return this.state[key]; }
}

const storeA = new Store();
const storeB = new Store();
storeA.set("user", "Alice");
console.log(storeB.get("user")); // "Alice" — same instance
console.log(storeA === storeB);   // true ✓
Overuse Warning
Singletons are essentially global state. Overusing them makes code hard to test (mocking a singleton is painful) and creates hidden coupling. Prefer dependency injection where testability matters.

Factory Pattern Creational

The Factory pattern provides an interface for creating objects without specifying their exact class. A factory function (or method) decides which concrete object to instantiate based on the inputs it receives.

When to use: Creating different types of UI components, HTTP clients for different environments (mock vs real), or any situation where the exact type of object to create is determined at runtime.
JavaScript — Factory Function
// Different notification "types" from one factory
function createNotification(type, message) {
  const base = {
    message,
    timestamp: new Date().toISOString(),
    show() { console.log(`[${this.type}] ${this.message}`); },
  };

  const types = {
    success: { ...base, type: "SUCCESS", icon: "✅" },
    error  : { ...base, type: "ERROR",   icon: "❌" },
    warning: { ...base, type: "WARNING", icon: "⚠️" },
    info   : { ...base, type: "INFO",    icon: "ℹ️" },
  };

  if (!types[type]) throw new Error(`Unknown type: ${type}`);
  return types[type];
}

const ok  = createNotification("success", "File saved!");
const err = createNotification("error",   "Network failed");
ok.show();    // [SUCCESS] File saved!
err.show();   // [ERROR] Network failed
JavaScript — Abstract Factory (HTTP client)
// Real client uses fetch; test client returns mocked data
function createHttpClient(env = "real") {
  if (env === "mock") {
    return {
      get: async (url) => ({ data: `Mocked GET ${url}` }),
      post: async (url, body) => ({ data: `Mocked POST ${url}` }),
    };
  }

  return {
    get: async (url) => {
      const res = await fetch(url);
      return res.json();
    },
    post: async (url, body) => {
      const res = await fetch(url, {
        method: "POST",
        body  : JSON.stringify(body),
        headers: { "Content-Type": "application/json" },
      });
      return res.json();
    },
  };
}

// Swap environments without touching business logic
const http = createHttpClient(process.env.NODE_ENV === "test" ? "mock" : "real");

Module Pattern Structural

The Module pattern uses closures to create private scope, exposing only what the consumer needs via a public API — the JS equivalent of access modifiers (private / public) in class-based languages.

When to use: Encapsulating utilities, counters, caches, or any logic that needs private state but a clean public interface. Today's ES Modules (import / export) are the standard, but the IIFE form is still valuable in legacy or bundleless environments.
JavaScript — Revealing Module Pattern
const CartModule = (() => {
  // Private state — not accessible from outside
  let _items = [];

  function _total() {
    return _items.reduce((sum, i) => sum + i.price * i.qty, 0);
  }

  // Public API — only these are revealed
  return {
    add(item)   { _items.push(item); },
    remove(id) { _items = _items.filter(i => i.id !== id); },
    items()    { return [..._items]; },  // shallow copy — no mutation
    total()    { return _total(); },
    clear()    { _items = []; },
  };
})();

CartModule.add({ id: 1, name: "Pen", price: 20, qty: 3 });
CartModule.add({ id: 2, name: "Book", price: 150, qty: 1 });
console.log(CartModule.total());   // 210
console.log(CartModule._items);   // undefined — private! ✓
Advertisement

Observer Pattern Behavioural

The Observer (also called Pub/Sub) pattern defines a one-to-many dependency between objects so that when one object (the subject) changes state, all its registered observers are notified automatically. This is the foundation of event systems and reactive programming.

When to use: Custom event emitters, state management stores (like Redux / Zustand), reactive UI updates, analytics tracking, and any decoupled communication between modules.
JavaScript — EventEmitter (Observer)
class EventEmitter {
  constructor() {
    this._events = {};       // { eventName: [fn, fn, ...] }
  }

  on(event, listener) {
    (this._events[event] ??= []).push(listener);
    return this;            // chainable
  }

  off(event, listener) {
    this._events[event] = (this._events[event] || [])
      .filter(l => l !== listener);
    return this;
  }

  emit(event, ...args) {
    (this._events[event] || []).forEach(l => l(...args));
    return this;
  }

  once(event, listener) {
    const wrapper = (...args) => {
      listener(...args);
      this.off(event, wrapper);  // auto-remove after first fire
    };
    return this.on(event, wrapper);
  }
}

// ── Usage ─────────────────────────────────────────────
const bus = new EventEmitter();

bus.on("login", user => console.log(`🔑 Logged in: ${user.name}`));
bus.on("login", user => console.log(`📊 Tracking login for: ${user.id}`));

bus.emit("login", { id: 42, name: "Alice" });
// 🔑 Logged in: Alice
// 📊 Tracking login for: 42
Built-in equivalent
The browser's EventTarget API (addEventListener / dispatchEvent) and Node.js's events.EventEmitter are both Observer pattern implementations — you don't always need a custom one.

Strategy Pattern Behavioural

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime — without changing the code that uses them.

When to use: Multiple sorting/searching algorithms, payment processing (credit card, UPI, wallet), form validation rules that differ per context, or any situation involving a choice between algorithms.
JavaScript — Strategy (Shipping Calculator)
// Each strategy is just a function (or object with a calculate method)
const ShippingStrategies = {
  standard : (weight) => weight * 5,
  express  : (weight) => weight * 12 + 50,
  overnight: (weight) => weight * 20 + 100,
};

class ShippingCalculator {
  constructor(strategy = "standard") {
    this._strategy = ShippingStrategies[strategy];
  }

  setStrategy(name) {
    if (!ShippingStrategies[name]) throw new Error("Unknown strategy");
    this._strategy = ShippingStrategies[name];
  }

  calculate(weight) {
    return this._strategy(weight);
  }
}

const calc = new ShippingCalculator();
console.log(calc.calculate(3));  // 15  (standard)

calc.setStrategy("express");
console.log(calc.calculate(3));  // 86  (express)

Decorator Pattern Structural

The Decorator pattern wraps an existing object or function to add new behaviour without modifying its source code — a form of composition over inheritance.

When to use: Adding logging / caching / authentication to functions, Higher-Order Components (HOCs) in React, middleware pipelines (Express.js), or TypeScript class decorators.
JavaScript — Function Decorator
// ── Logging decorator ─────────────────────────────────
function withLogging(fn) {
  return function (...args) {
    console.log(`▶ Calling ${fn.name}(${args.join(", ")})`);
    const result = fn.apply(this, args);
    console.log(`◀ ${fn.name} returned: ${result}`);
    return result;
  };
}

// ── Memoisation (caching) decorator ───────────────────
function withMemo(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

// Original function — untouched
function add(a, b) { return a + b; }

// Compose decorators
const loggedAdd = withLogging(withMemo(add));
loggedAdd(3, 4);   // ▶ add(3, 4) → ◀ returned 7
loggedAdd(3, 4);   // ▶ add(3, 4) → ◀ returned 7  (from cache)

Proxy Pattern Structural

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. ES6 ships a native Proxy object that makes this trivial to implement.

When to use: Input validation, property access logging, lazy initialisation, change detection (used internally by Vue 3's reactivity), and access control.
JavaScript — ES6 Proxy (Validation)
const userSchema = {
  name : "string",
  age  : "number",
  email: "string",
};

function createValidatedUser(initial = {}) {
  return new Proxy({ ...initial }, {
    set(target, prop, value) {
      const expected = userSchema[prop];
      if (expected && typeof value !== expected) {
        throw new TypeError(
          `"${prop}" must be a ${expected}, got ${typeof value}`
        );
      }
      target[prop] = value;
      return true;
    },
    get(target, prop) {
      if (!(prop in target)) console.warn(`"${prop}" does not exist`);
      return target[prop];
    },
  });
}

const user    = createValidatedUser({ name: "Alice", age: 25 });
user.email     = "alice@example.com";   // ✓
user.age       = "twenty";              // ✗ TypeError: "age" must be a number
Advertisement

Best Practices

⚡
Free Resource
Download our JavaScript Cheat Sheet
Design Patterns, ES6+, async/await, DOM — all in one printable page.
Get Sheet
✓ Do
  • Choose a pattern because it solves your problem — not for the sake of using a pattern
  • Prefer composition over inheritance (Decorator, Strategy)
  • Remove Observer listeners when they are no longer needed to prevent memory leaks
  • Keep Singleton state minimal and clearly documented as global
  • Use native ES Modules (import/export) for the Module pattern in modern code
  • Test each pattern in isolation — patterns increase testability when used correctly
✗ Don't
  • Over-engineer simple problems with unnecessary patterns (YAGNI)
  • Treat Singleton as a catch-all for global state — use a proper state manager
  • Create deep inheritance chains — they tightly couple code and resist change
  • Forget to unsubscribe from an Observer — this causes memory leaks in SPAs
  • Mix multiple patterns in one class until it becomes unreadable
  • Use the Proxy pattern's get trap for silent property creation — it hides bugs
Quick Check — Chapter 62

Which design pattern ensures that a class has only one instance and provides a global access point to it?

Chapter Summary
  • Design patterns are named, reusable solutions to common software problems — not copy-paste code, but templates to adapt.
  • The three GoF categories: Creational (object creation), Structural (composition), Behavioural (communication).
  • Singleton — one instance via closure or a static private field; avoid for highly-tested logic.
  • Factory — delegate object construction to a function; great for environment-specific or type-driven creation.
  • Module — use closures / IIFE to create private scope and expose a clean public API.
  • Observer — pub/sub via on / emit / off; always remove listeners when done.
  • Strategy — swap algorithms at runtime; keeps conditionals out of business logic.
  • Decorator — wrap functions to add logging, caching, or auth without touching the original.
  • Proxy — intercept get / set with ES6 Proxy for validation and change detection.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel