Sitemap
Harikrishna Bomen

Harikrishna Bomen

JavaScript Design Patterns

4 min readAug 13, 2025

--

Why patterns?

They give reusable solutions to recurring problems, improve readability, and create shared vocabulary for teams. In JS, patterns adapt to prototypes, first-class functions, modules, and async behaviour.

1) Creational Design Patterns

1.1 Factory

Use when: You need to create objects without exposing construction logic or to return different sub-types based on input.

class Payment { constructor(amount){ this.amount = amount; } }
class CardPayment extends Payment { type = 'card' }
class UpiPayment extends Payment { type = 'upi' }

function paymentFactory(method, amount) {
if (method === 'card') return new CardPayment(amount);
if (method === 'upi') return new UpiPayment(amount);
throw new Error('Unsupported method');
}

Pitfalls: Overuse leads to indirection; prefer straightforward new when simple.

1.2 Singleton

Use when: Exactly one shared instance (e.g., config, cache).

class Config {
constructor() {
if (Config.instance) return Config.instance;
this.env = 'prod';
Config.instance = this;
}
}
const c1 = new Config(), c2 = new Config(); // same instance

Modern tip: For true module-wide singletons, just export module-level state.

// config.js
export const config = { env: 'prod' }; // single instance per module graph

1.3 Builder

Use when: Complex object construction with many optional parts.

class Query {
constructor(){ this._parts = []; }
select(cols){ this._parts.push(`SELECT ${cols}`); return this; }
from(t){ this._parts.push(`FROM ${t}`); return this; }
where(w){ this._parts.push(`WHERE ${w}`); return this; }
build(){ return this._parts.join(' '); }
}
const sql = new Query().select('*').from('users').where('id=1').build();

1.4 Prototype

Use when: Clone existing objects instead of building from scratch.

const userProto = { greet(){ return `Hi, ${this.name}`; } };
const u1 = Object.create(userProto, { name: { value: 'Hari', writable: true }});

2) Structural Patterns

2.1 Module (ES Modules)

Use when: Encapsulation + public API.

// counter.js
let count = 0;
export function inc(){ count++; }
export function get(){ return count; }

2.2 Adaptor

Use when: Make incompatible interfaces work together.

function legacyLog(msg){ console.log(`[LEGACY]: ${msg}`); }
const logger = {
info: (m) => legacyLog(m),
error: (m) => legacyLog(`ERROR ${m}`)
};
// Now code expecting logger.info/error works.

2.3 Decorator

Use when: Add behaviour dynamically without changing original code.

function withCache(fn) {
const cache = new Map();
return (x) => cache.has(x) ? cache.get(x) : (cache.set(x, fn(x)), cache.get(x));
}
const slowSquare = n => { /* heavy */ return n*n; };
const fastSquare = withCache(slowSquare);

Note: Different from ES decorator syntax for classes/properties.

2.4 Facade

Use when: Provide a simple API over complex subsystems.

const http = {
async getJSON(url){ const r = await fetch(url); return r.json(); },
postJSON(url, data){ return fetch(url, { method:'POST', body: JSON.stringify(data) }); }
};

2.5 Proxy

Use when: Control access (validation, lazy, virtual, logging).

const user = { name: 'Hari' };
const observed = new Proxy(user, {
set(target, key, val) {
console.log('set', key, val);
target[key] = val;
return true;
}
});
observed.name = 'Krishna';

3) Behavioural Patterns

3.1 Observer (Pub/Sub)

Use when: One-to-many notifications (UI, state stores).

class EventBus {
#map = new Map();
on(evt, h){ (this.#map.get(evt) ?? this.#map.set(evt, []).get(evt)).push(h); }
emit(evt, data){ (this.#map.get(evt) || []).forEach(h => h(data)); }
}
const bus = new EventBus();
bus.on('login', u => console.log('Welcome', u));
bus.emit('login', { name: 'Hari' });

React note: Component subscriptions; Redux uses a similar idea.

3.2 Strategy

Use when: Swap algorithms at runtime.

const strategies = {
asc: (a,b)=>a-b,
desc:(a,b)=>b-a
};
function sort(arr, mode='asc'){ return [...arr].sort(strategies[mode]); }

3.3 Command

Use when: Encapsulate actions (undo/redo, queues).

function createAddCommand(list, item){
return {
execute(){ list.push(item); },
undo(){ list.pop(); }
};
}
const list = [];
const cmd = createAddCommand(list, 'x');
cmd.execute(); cmd.undo();

3.4 Iterator

Use when: Custom traversal.

const range = (start, end) => ({
[Symbol.iterator](){
let i = start;
return { next(){ return i<=end ? { value: i++, done:false } : { done:true }; } }
}
});
for (const n of range(1,3)) console.log(n);

3.5 State

Use when: Behaviour changes with internal state.

class Light {
#state = 'off';
press(){
if (this.#state==='off'){ console.log('on'); this.#state='on'; }
else { console.log('off'); this.#state='off'; }
}
}

3.6 Mediator

Use when: Reduce direct coupling between many objects.

class Chat {
users = new Set();
join(user){ this.users.add(user); user.chat = this; }
send(from, msg){ this.users.forEach(u => u!==from && u.receive(msg)); }
}

4) Async & Concurrency Patterns (JS-specific)

  • Promise chaining (sequence)
  • Promise.all / all Settled / any (fan-out/fan-in)
  • Queue/Pool (limit concurrency)
async function pool(tasks, limit=3){
const ret = []; let i=0; const running = new Set();
async function runNext(){
if (i >= tasks.length) return;
const p = tasks[i++]().finally(()=> running.delete(p));
running.add(p); ret.push(p);
if (running.size < limit) await runNext();
else await Promise.race(running).then(runNext);
}
await runNext();
return Promise.all(ret);
}

Choosing the Right Pattern (Rule of Thumb)

  • Encapsulation/API → Module, Facade
  • Many listeners → Observer
  • Swap algorithm → Strategy
  • Access control/logging → Proxy
  • Complex object creation → Builder/Factory
  • Undo/redo, queues → Command
  • Shared global state → Singleton (prefer module export)

Common Pitfalls

  • Over-patterning (YAGNI).
  • Singleton misuse → hidden global state, hard tests.
  • Factories without need → extra indirection.
  • Observer leaks → remember to unsubscribe.
  • Proxy performance pitfalls if trapping hot paths.

Quick Interview Cheats

  • Be ready to define, draw a tiny diagram, code a 10–15 line example, and state a real-world use.
  • Connect to frameworks:

React: Observer (state updates), Decorator (HOCs), Strategy (rendering choices), Module (hooks/modules).

Get Harikrishna Bomen’s stories in your inbox

Join Medium for free to get updates from this writer.

Node: Module, Factory (drivers), Proxy (validation), Observer (EventEmitter).

Mini Practice Tasks

  1. Decorator: Write withRetry(fn, retries) that retries a failing async function.
  2. Strategy: Build a formatter with json, csv, xml strategies.
  3. Observer: Simple EventEmitter with on, off, emit.
  4. Proxy: Validate object properties (non-empty strings, ranges).
  5. Factory: Create a shapeFactory returning draw() for Circle/Square.

--

--