Full answer
Design patterns are common solutions to recurring problems. In JavaScript, language features often make them smaller.
Module pattern: before ES modules, an IIFE (immediately invoked function expression) created a private scope and returned a public object, which gave private state through closure: const counter = (() => { let n = 0; return { inc: () => ++n }; })(). Today, every ES module file is already a private scope. Anything not exported is private, and the exports form the public API. Use the file, and use closures or #private fields for per-instance privacy.
Singleton: a class or object that must exist once, such as a configuration object, a logger, or a database connection pool. The classic version stores the instance in a static property and returns it from getInstance(). In JavaScript, simpler options exist. A module is evaluated once and cached, so export const logger = new Logger() gives every importer the same instance. The same applies to require through the require.cache. Caveats: the cache is per module path and per realm, so duplicate copies of a package in node_modules, or the same file loaded through different URLs or in a worker, create separate instances. Singletons are global state: they make testing harder (state leaks between tests) and hide dependencies. Prefer passing the instance in (dependency injection), and keep the singleton as the default wiring.
Factory: a function (or static method) that returns objects without exposing how they are built. Uses: choosing the right class by input (createShape('circle')), applying defaults and validation, returning plain objects with closures for privacy, and creating test doubles. A factory function avoids new and this, so there are no binding problems, and it can return different types. A registry (a Map from type name to constructor) makes factories extensible without a long switch.
When asked in interviews, give a short definition, the modern JavaScript form, and one downside for each. For singletons the downside is global state, for factories it is indirection, and for modules it is that circular imports can break initialization.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// Module pattern with an IIFE: n is private
const counter = (() => {
let n = 0;
return { inc: () => ++n, get value() { return n; } };
})();
counter.inc();
counter.inc();
console.log('module pattern:', counter.value, counter.n);
// Singleton with a static instance
class Logger {
static #instance;
#lines = [];
constructor() {
if (Logger.#instance) return Logger.#instance;
Logger.#instance = this;
}
log(line) {
this.#lines.push(line);
return this;
}
get count() {
return this.#lines.length;
}
}
const a = new Logger();
const b = new Logger();
a.log('one');
b.log('two');
console.log('singleton:', a === b, a.count);
// Singleton through the module cache
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'singleton-'));
fs.writeFileSync(path.join(dir, 'config.js'), 'module.exports = { loads: (globalThis.__loads = (globalThis.__loads ?? 0) + 1) };');
const first = require(path.join(dir, 'config.js'));
const second = require(path.join(dir, 'config.js'));
console.log('module cache gives one instance:', first === second, 'module ran', globalThis.__loads, 'time(s)');
delete require.cache[require.resolve(path.join(dir, 'config.js'))];
console.log('after clearing the cache a new instance appears:', require(path.join(dir, 'config.js')) !== first, 'runs:', globalThis.__loads);
fs.rmSync(dir, { recursive: true, force: true });
// Factory with a registry
class Circle { constructor({ r }) { this.area = Math.PI * r * r; } }
class Rect { constructor({ w, h }) { this.area = w * h; } }
const registry = new Map([['circle', Circle], ['rect', Rect]]);
function createShape(type, options) {
const Shape = registry.get(type);
if (!Shape) throw new RangeError(`Unknown shape: ${type}`);
return new Shape(options);
}
console.log(createShape('circle', { r: 1 }).area.toFixed(2), createShape('rect', { w: 2, h: 3 }).area);
registry.set('square', class Square extends Rect { constructor({ s }) { super({ w: s, h: s }); } });
console.log(createShape('square', { s: 4 }).area);
try {
createShape('hexagon', {});
} catch (error) {
console.log(error.message);
}
// Factory function with closure privacy and no new
function createAccount(owner, balance = 0) {
return {
owner,
deposit(amount) { balance += amount; return balance; },
get balance() { return balance; },
};
}
const account = createAccount('Asha', 10);
account.deposit(5);
console.log(account.balance, Object.keys(account));Run with Node.js v24.22.1 as js-143.js; two runs gave identical output. Output: module pattern: 2 undefined singleton: true 2 module cache gives one instance: true module ran 1 time(s) after clearing the cache a new instance appears: true runs: 2 3.14 6 16 Unknown shape: hexagon 15 [ 'owner', 'deposit', 'balance' ]
Key points
- Module pattern: private state in an IIFE closure, or simply an ES module file with exports as the API.
- Singleton: one shared instance; the module cache gives it for free, but duplicate copies break it.
- Singletons are global state that complicates tests; prefer injection with a default instance.
- Factory: a function that builds objects, hiding construction, choosing types, and avoiding new and this.
- A registry Map makes a factory extensible; each pattern has a trade-off to state.
Common mistakes
- Using a singleton for state that tests need to reset.
- Assuming a module is loaded once when two copies of the package exist.
- Using long switch statements in factories instead of a registry.
- Using classes with static getInstance in JavaScript when a module export is enough.
Follow-ups
- How does dependency injection reduce the problems of singletons?
- Why can the same module be evaluated twice in a project?
- How does the factory pattern help when writing tests?
Tips
- Give the modern form of each pattern, not only the textbook version.
- Mention the module cache as the natural singleton.
- State one downside for each pattern.