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 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:
| 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.
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 ✓
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 ✓
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.
// 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
// 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.
import /
export) are the standard, but the IIFE form is still valuable in legacy or
bundleless environments.
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! ✓
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.
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
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.
// 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.
// ── 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.
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
Best Practices
- 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
- 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
gettrap for silent property creation — it hides bugs
Which design pattern ensures that a class has only one instance and provides a global access point to it?
- 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/setwith ES6Proxyfor validation and change detection.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.