JavaScript · Syntax · Advanced

Design patterns

10 tasks

Reusable solutions to common structural and behavioural problems. Covers Observer, Strategy, Factory, and Decorator pattern in plain JavaScript.

Why patterns, Observer with memory-leak warning, Strategy

#
**Why design patterns matter** Design patterns are named solutions to recurring design problems. They aren't code you copy — they're a vocabulary. When a colleague says 'this should be an Observer', you both immediately understand the structure without a long explanation. In JavaScript specifically, many classic OOP patterns have simpler functional equivalents — knowing both lets you choose what's readable for the situation. **Observer pattern — subscribe/notify** Observer decouples producers of events from consumers. Producers don't know who is listening; consumers don't know who fires. This is the foundation of DOM events, Node.js EventEmitter, and state management libraries: ```js class EventEmitter { constructor() { this._listeners = {}; } on(event, fn) { (this._listeners[event] ??= []).push(fn); } off(event, fn) { this._listeners[event] = (this._listeners[event] || []).filter(l => l !== fn); } emit(event, ...args) { (this._listeners[event] || []).forEach(fn => fn(...args)); } once(event, fn) { const wrap = (...a) => { fn(...a); this.off(event, wrap); }; this.on(event, wrap); } } ``` **Memory leak warning:** listeners registered with `.on()` keep a reference to the callback. If you attach listeners to a long-lived emitter from a short-lived component (e.g. a React component), you *must* call `.off()` on unmount, otherwise the callback and everything it closes over stays in memory: ```js // BUG: handler is never removed class Widget { mount() { bus.on('data', this.handleData); } // destroy() is missing — memory leak! } // CORRECT: class Widget { mount() { bus.on('data', this.handleData); } destroy() { bus.off('data', this.handleData); } } ``` **Strategy pattern — swap algorithms at runtime** ```js class Sorter { constructor(strategy) { this.strategy = strategy; } sort(arr) { return this.strategy([...arr]); } } const asc = arr => arr.sort((a, b) => a - b); const desc = arr => arr.sort((a, b) => b - a); const s = new Sorter(asc); s.sort([3, 1, 2]); // [1, 2, 3] s.strategy = desc; s.sort([3, 1, 2]); // [3, 2, 1] ``` In JavaScript, Strategy is often just 'pass a function as an argument' — no class needed.

Factory, Decorator (HOF + pipe), Command with undo/redo

#
**Factory pattern — hide creation details** ```js function createUser(role) { const base = { role, createdAt: new Date() }; if (role === 'admin') return { ...base, permissions: ['read', 'write', 'delete'] }; if (role === 'viewer') return { ...base, permissions: ['read'] }; throw new Error(`Unknown role: ${role}`); } createUser('admin'); // { role:'admin', permissions:[...], createdAt:... } ``` Factory is useful when: the creation logic is complex, you want to return different subclasses based on input, or you need to cache/pool instances. **Decorator pattern — wrap to extend (functional style)** In JS, Decorator is naturally a higher-order function: ```js // Timing decorator const withTiming = fn => (...args) => { const t = performance.now(); const result = fn(...args); console.log(`${fn.name} took ${(performance.now() - t).toFixed(2)}ms`); return result; }; // Memoize decorator const memoize = fn => { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (!cache.has(key)) cache.set(key, fn(...args)); return cache.get(key); }; }; // Compose decorators with pipe: const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x); const timedMemoFib = pipe(memoize, withTiming)(fib); ``` **Command pattern — encapsulate actions for undo/redo** Command wraps an operation as an object, making it possible to queue, log, undo, or replay operations: ```js class TextEditor { constructor() { this.text = ''; this.history = []; } execute(command) { command.execute(this); this.history.push(command); } undo() { this.history.pop()?.undo(this); } } const insertCmd = text => ({ execute: editor => { editor.text += text; }, undo: editor => { editor.text = editor.text.slice(0, -text.length); }, }); const editor = new TextEditor(); editor.execute(insertCmd('Hello')); editor.execute(insertCmd(' world')); console.log(editor.text); // 'Hello world' editor.undo(); console.log(editor.text); // 'Hello' ```

Pattern table, functional alternatives, when not to, recognition guide

#
**Pattern comparison** | Pattern | Problem it solves | JS idiom | |---|---|---| | Observer | Decouple event producers from consumers | `EventEmitter`, `addEventListener` | | Strategy | Swap algorithm/behaviour at runtime | Pass function as argument | | Factory | Hide object creation complexity | Function returning object/class | | Decorator | Add behaviour without modifying original | Higher-order function | | Command | Encapsulate actions; enable undo/queue | Object with `execute`/`undo` | | Singleton | One shared instance app-wide | Module-level `const inst = new X()` | **Functional alternatives — often simpler in JS** ```js // Strategy — just pass the function: function process(data, transform) { return transform(data); } process(data, x => x * 2); process(data, x => x + 10); // Decorator — compose with pipe: const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x); const sanitize = pipe(trim, lowercase, removeSpecialChars); // Singleton — module itself acts as singleton: // config.js export const config = { debug: false, version: '1.0' }; // Everyone who imports config gets the same object ``` **When NOT to use patterns** - Don't use Observer when a function is called in one place — just call it directly - Don't use Factory when `new MyClass(arg)` is already readable enough - Don't use Singleton for stateless utilities — just export functions - Patterns solve *communication* problems between components, not computation. If you're applying a pattern to a single function, step back — it's probably overkill **Recognising patterns in the wild** | You see... | Pattern | |---|---| | `.addEventListener` / `.on()` / `.subscribe()` | Observer | | Function passed as config option | Strategy | | `createX()` function instead of `new X()` | Factory | | Function wrapping function (`withX(fn)`) | Decorator | | `execute()` + `undo()` pair | Command | | Module-level cached instance | Singleton |
01

Observer: EventEmitter class

#

Implement an `EventEmitter` class with three methods: `on(event, listener)` — register a listener; `off(event, listener)` — remove a listener; `emit(event, ...args)` — call all listeners for that event with the given args.

class EventEmitter {
  constructor() {
    this._listeners = {};
  }

  on(event, listener) {
    // register listener
  }

  off(event, listener) {
    // remove listener
  }

  emit(event, ...args) {
    // call all listeners
  }
}

const emitter = new EventEmitter();
const greet = name => console.log(`Hello, ${name}!`);
emitter.on('greet', greet);
emitter.emit('greet', 'Alice');  // Hello, Alice!
emitter.emit('greet', 'Bob');    // Hello, Bob!
emitter.off('greet', greet);
emitter.emit('greet', 'Carol');  // (nothing)
Solution
class EventEmitter {
  constructor() {
    this._listeners = {};
  }

  on(event, listener) {
    if (!this._listeners[event]) this._listeners[event] = [];
    this._listeners[event].push(listener);
  }

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

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

const emitter = new EventEmitter();
const greet = name => console.log(`Hello, ${name}!`);
emitter.on('greet', greet);
emitter.emit('greet', 'Alice');  // Hello, Alice!
emitter.emit('greet', 'Bob');    // Hello, Bob!
emitter.off('greet', greet);
emitter.emit('greet', 'Carol');  // (nothing)
02

Observer: once() — fire only once

#

Add an `once(event, listener)` method to `EventEmitter`. It should register a listener that is automatically removed after it fires once.

class EventEmitter {
  constructor() { this._listeners = {}; }

  on(event, fn) {
    if (!this._listeners[event]) this._listeners[event] = [];
    this._listeners[event].push(fn);
  }

  off(event, fn) {
    if (!this._listeners[event]) return;
    this._listeners[event] = this._listeners[event].filter(l => l !== fn);
  }

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

  once(event, fn) {
    // fires fn once, then auto-removes
  }
}

const ee = new EventEmitter();
ee.once('connect', () => console.log('connected!'));
ee.emit('connect');  // connected!
ee.emit('connect');  // (nothing)
Solution
class EventEmitter {
  constructor() { this._listeners = {}; }

  on(event, fn) {
    if (!this._listeners[event]) this._listeners[event] = [];
    this._listeners[event].push(fn);
  }

  off(event, fn) {
    if (!this._listeners[event]) return;
    this._listeners[event] = this._listeners[event].filter(l => l !== fn);
  }

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

  once(event, fn) {
    const wrapper = (...args) => {
      fn(...args);
      this.off(event, wrapper);
    };
    this.on(event, wrapper);
  }
}

const ee = new EventEmitter();
ee.once('connect', () => console.log('connected!'));
ee.emit('connect');  // connected!
ee.emit('connect');  // (nothing)
03

Strategy: swap sorting algorithms

#

Create a `Sorter` class with a `sort(arr)` method. The sorting algorithm is injected via the constructor as a strategy function. Support at least two strategies: bubble sort and built-in sort. Demonstrate swapping strategies at runtime.

class Sorter {
  constructor(strategy) {
    this.strategy = strategy;
  }

  sort(arr) {
    return this.strategy([...arr]);
  }
}

const bubbleSort = arr => {
  // implement bubble sort
};

const nativeSort = arr => arr.sort((a, b) => a - b);

const sorter = new Sorter(bubbleSort);
console.log(sorter.sort([3, 1, 4, 1, 5])); // [1, 1, 3, 4, 5]

sorter.strategy = nativeSort;              // swap strategy
console.log(sorter.sort([9, 2, 7]));       // [2, 7, 9]
Solution
class Sorter {
  constructor(strategy) {
    this.strategy = strategy;
  }

  sort(arr) {
    return this.strategy([...arr]);
  }
}

const bubbleSort = arr => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
    }
  }
  return arr;
};

const nativeSort = arr => arr.sort((a, b) => a - b);

const sorter = new Sorter(bubbleSort);
console.log(sorter.sort([3, 1, 4, 1, 5])); // [1, 1, 3, 4, 5]

sorter.strategy = nativeSort;
console.log(sorter.sort([9, 2, 7]));        // [2, 7, 9]
04

Strategy: payment methods

#

Create a `Checkout` class with a `pay(amount)` method. Three payment strategies: `creditCard`, `paypal`, and `crypto` — each is a function that takes an amount and logs a payment message. The strategy is set via `checkout.setStrategy(fn)`.

const creditCard = amount => console.log(`Charged $${amount} to credit card`);
const paypal = amount => console.log(`Sent $${amount} via PayPal`);
const crypto = amount => console.log(`Transferred $${amount} in BTC`);

class Checkout {
  setStrategy(strategy) {
    this.strategy = strategy;
  }

  pay(amount) {
    // call this.strategy
  }
}

const checkout = new Checkout();
checkout.setStrategy(creditCard);
checkout.pay(50);   // Charged $50 to credit card

checkout.setStrategy(paypal);
checkout.pay(30);   // Sent $30 via PayPal
Solution
const creditCard = amount => console.log(`Charged $${amount} to credit card`);
const paypal = amount => console.log(`Sent $${amount} via PayPal`);
const crypto = amount => console.log(`Transferred $${amount} in BTC`);

class Checkout {
  setStrategy(strategy) {
    this.strategy = strategy;
  }

  pay(amount) {
    if (!this.strategy) throw new Error('No payment strategy set');
    this.strategy(amount);
  }
}

const checkout = new Checkout();
checkout.setStrategy(creditCard);
checkout.pay(50);   // Charged $50 to credit card

checkout.setStrategy(paypal);
checkout.pay(30);   // Sent $30 via PayPal

checkout.setStrategy(crypto);
checkout.pay(100);  // Transferred $100 in BTC
05

Factory: shape creator

#

Write a factory function `createShape(type, ...dims)` that creates shape objects. Supported types: `'circle'` (radius), `'rect'` (width, height). Each shape object must have an `area()` method. Throw an error for unknown types.

function createShape(type, ...dims) {
  // return shape object based on type
}

const c = createShape('circle', 5);
console.log(c.area().toFixed(2)); // 78.54

const r = createShape('rect', 4, 3);
console.log(r.area());             // 12

createShape('triangle', 3, 4, 5); // Error: Unknown shape: triangle
Solution
function createShape(type, ...dims) {
  switch (type) {
    case 'circle': {
      const [r] = dims;
      return { type: 'circle', area: () => Math.PI * r * r };
    }
    case 'rect': {
      const [w, h] = dims;
      return { type: 'rect', area: () => w * h };
    }
    default:
      throw new Error(`Unknown shape: ${type}`);
  }
}

const c = createShape('circle', 5);
console.log(c.area().toFixed(2)); // 78.54

const r = createShape('rect', 4, 3);
console.log(r.area());             // 12
06

Decorator: add logging to any function

#

Write a `withLogging(fn)` decorator that wraps any function. Before calling the original, log `'Calling <fn.name> with <args>'`. After it returns, log `'<fn.name> returned <result>'`. Return a new function with the same signature.

function withLogging(fn) {
  return function(...args) {
    // log before call
    // call fn
    // log after
    // return result
  };
}

function add(a, b) { return a + b; }

const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// Calling add with 2,3
// add returned 5
Solution
function withLogging(fn) {
  return function(...args) {
    console.log(`Calling ${fn.name} with ${args}`);
    const result = fn(...args);
    console.log(`${fn.name} returned ${result}`);
    return result;
  };
}

function add(a, b) { return a + b; }

const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// Calling add with 2,3
// add returned 5
07

Decorator: memoize

#

Write a `memoize(fn)` decorator that caches results by arguments. On repeated calls with the same args, return the cached value without re-running `fn`. Use a `Map` for the cache. Test with a slow `factorial` that logs when it actually runs.

function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    // check cache, compute if miss, store and return
  };
}

function factorial(n) {
  console.log(`Computing factorial(${n})`);
  return n <= 1 ? 1 : n * factorial(n - 1);
}

const memoFactorial = memoize(factorial);
console.log(memoFactorial(5));  // logs Computing 5..1, returns 120
console.log(memoFactorial(5));  // no 'Computing' logs — cached
console.log(memoFactorial(3));  // logs Computing 3..1
Solution
function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

function factorial(n) {
  console.log(`Computing factorial(${n})`);
  return n <= 1 ? 1 : n * factorial(n - 1);
}

const memoFactorial = memoize(factorial);
console.log(memoFactorial(5));
console.log(memoFactorial(5));  // cached, no Computing logs
08

Singleton: module-level instance

#

Implement a `Logger` singleton using the ES module pattern. The module exports a single `logger` instance. All importers should share the same instance — logged messages accumulate across calls. Show that calling `logger.log()` from two different 'files' adds to the same log.

// logger.js
class Logger {
  constructor() {
    this.messages = [];
  }
  log(msg) {
    this.messages.push(msg);
    console.log(`[LOG] ${msg}`);
  }
  getAll() { return this.messages; }
}

export const logger = new Logger();  // single instance

// fileA.js
import { logger } from './logger.js';
logger.log('Event from A');

// fileB.js
import { logger } from './logger.js';
logger.log('Event from B');
console.log(logger.getAll()); // ['Event from A', 'Event from B']
Solution
// logger.js
class Logger {
  constructor() { this.messages = []; }
  log(msg) { this.messages.push(msg); console.log(`[LOG] ${msg}`); }
  getAll() { return this.messages; }
}

export const logger = new Logger();

// In Node.js or bundled code, both imports return the same object.
// Simulating two files in one script:
const logger1 = { messages: [], log(m) { this.messages.push(m); }, getAll() { return this.messages; } };
const logger2 = logger1;  // same reference

logger1.log('Event from A');
logger2.log('Event from B');
console.log(logger1.getAll()); // ['Event from A', 'Event from B']
09

Functional composition as decoration

#

Write a `compose(...fns)` function that returns a new function applying the given functions right-to-left. Then use it to build a text pipeline: `trim` -> `lowercase` -> `exclaim` (add `!`). Composing these three produces a function that applies all three in sequence.

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

const trim = s => s.trim();
const lowercase = s => s.toLowerCase();
const exclaim = s => s + '!';

const process = compose(exclaim, lowercase, trim);
console.log(process('  Hello World  ')); // hello world!
Solution
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

const trim = s => s.trim();
const lowercase = s => s.toLowerCase();
const exclaim = s => s + '!';

const process = compose(exclaim, lowercase, trim);
console.log(process('  Hello World  ')); // hello world!

// Also try pipe (left-to-right):
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const process2 = pipe(trim, lowercase, exclaim);
console.log(process2('  Hello World  ')); // hello world!
10

Observer: typed event bus with payload

#

Create an `EventBus` where events carry typed payloads. `subscribe(type, handler)` — register a handler; `publish(type, payload)` — call all handlers for that type with the payload; `unsubscribe(type, handler)` — remove a handler. Demonstrate with a 'user:login' event carrying `{ userId, name }`.

class EventBus {
  constructor() { this._handlers = {}; }

  subscribe(type, handler) {
    // register handler
  }

  unsubscribe(type, handler) {
    // remove handler
  }

  publish(type, payload) {
    // call all handlers
  }
}

const bus = new EventBus();

const onLogin = ({ userId, name }) => console.log(`User ${name} (${userId}) logged in`);
bus.subscribe('user:login', onLogin);
bus.publish('user:login', { userId: 42, name: 'Alice' });
// User Alice (42) logged in

bus.unsubscribe('user:login', onLogin);
bus.publish('user:login', { userId: 99, name: 'Bob' }); // (nothing)
Solution
class EventBus {
  constructor() { this._handlers = {}; }

  subscribe(type, handler) {
    if (!this._handlers[type]) this._handlers[type] = [];
    this._handlers[type].push(handler);
  }

  unsubscribe(type, handler) {
    if (!this._handlers[type]) return;
    this._handlers[type] = this._handlers[type].filter(h => h !== handler);
  }

  publish(type, payload) {
    (this._handlers[type] || []).forEach(h => h(payload));
  }
}

const bus = new EventBus();
const onLogin = ({ userId, name }) => console.log(`User ${name} (${userId}) logged in`);
bus.subscribe('user:login', onLogin);
bus.publish('user:login', { userId: 42, name: 'Alice' });
bus.unsubscribe('user:login', onLogin);
bus.publish('user:login', { userId: 99, name: 'Bob' }); // (nothing)