Design Patterns in JavaScript: Singleton, Factory, Builder, Observer and More
A design pattern is a proven, named solution to a problem that keeps coming back. Knowing the names lets teams talk about structure quickly (“make it a factory”, “the reporter is an observer”), and almost every automation framework is built from a handful of them: the Page Object Model, test-data builders, a config singleton, reporters that listen to test events, and retry decorators around flaky calls. In this lesson you will implement the patterns that matter most in JavaScript and see each one in a testing context, plus when not to use them.
📖 What You’ll Learn: what design patterns are and the three families, the module pattern, singleton (and why modules already are singletons), factory functions, the builder pattern for test data, observer and publish/subscribe with EventEmitter, strategy, decorator (retry and timing wrappers), adapter, the Page Object Model as a pattern, and the pitfalls of over-engineering.
🧩 What Are Design Patterns?
Patterns are grouped into three families (from the classic “Gang of Four” book):
| Family | Solves | Patterns in this lesson |
|---|---|---|
| Creational | How objects are created | Singleton, Factory, Builder |
| Structural | How objects are composed | Module, Decorator, Adapter, Page Object |
| Behavioural | How objects communicate | Observer / Pub-Sub, Strategy |
JavaScript’s first-class functions, closures and modules make many patterns much lighter than in Java or C#: often a function replaces a whole class hierarchy.
📦 Module and Singleton
The module pattern hides private state and exposes a small public API. Before ES modules it was built with a closure (an IIFE); today every ES module file does this for you.
A singleton guarantees one shared instance, for example one configuration or one database connection pool. Because a module is evaluated only once and then cached, exporting an object from a module already gives you a singleton:
📄 package.json
{ "type": "module" }
📄 config.js
let loadCount = 0;
const settings = new Map(); // private: not exported
function load() {
loadCount++;
settings.set("baseURL", "https://staging.example.com");
settings.set("retries", 0);
}
load();
export const config = {
get: (key) => settings.get(key),
set: (key, value) => settings.set(key, value),
get loadCount() { return loadCount; },
};
📄 helpers.js
import { config } from "./config.js";
export const getBaseURL = () => `${config.get("baseURL")} (retries: ${config.get("retries")})`;
📄 app.js
import { config } from "./config.js";
import { getBaseURL } from "./helpers.js";
config.set("retries", 2); // change it in one file...
console.log(getBaseURL()); // ...and every importer sees the same instance
console.log(config.get("retries"), config.loadCount);
⌨️ Terminal
node app.js
🖥️ Output
https://staging.example.com (retries: 2)
2 1
⚠️ Watch out: Singletons are global state in disguise. Shared mutable state between tests makes them order-dependent. Keep singletons read-only (configuration), or reset them in test setup.
🏭 Factory
A factory creates objects without the caller knowing the exact class, choosing the right one from a parameter. In automation it picks the browser, the environment client or the reporter:
📄 factory.js
class ConsoleReporter { report(r) { return `[console] ${r.test}: ${r.status}`; } }
class JsonReporter { report(r) { return JSON.stringify(r); } }
class JUnitReporter { report(r) { return `<testcase name="${r.test}"${r.status === "failed" ? "><failure/></testcase>" : "/>"}`; } }
const reporters = { console: ConsoleReporter, json: JsonReporter, junit: JUnitReporter };
function createReporter(type) {
const Reporter = reporters[type];
if (!Reporter) throw new Error(`Unknown reporter "${type}". Use: ${Object.keys(reporters).join(", ")}`);
return new Reporter();
}
const result = { test: "login", status: "failed" };
for (const type of ["console", "json", "junit"]) console.log(createReporter(type).report(result));
try { createReporter("pdf"); } catch (e) { console.log(e.message); }
⌨️ Terminal
node factory.js
🖥️ Output
[console] login: failed
{"test":"login","status":"failed"}
<testcase name="login"><failure/></testcase>
Unknown reporter "pdf". Use: console, json, junit
Adding a new reporter now means adding one class and one map entry; no caller changes.
🏗️ Builder: Readable Test Data
A builder constructs a complex object step by step with readable, chainable methods and sensible defaults. It is the most useful pattern for test data: each test states only what matters to it:
📄 builder.js
class UserBuilder {
#user = {
name: "Test User",
email: "user@sqatools.in",
role: "viewer",
active: true,
address: { city: "Pune", country: "IN" },
};
withName(name) { this.#user.name = name; return this; }
withEmail(email) { this.#user.email = email; return this; }
asAdmin() { this.#user.role = "admin"; return this; }
inactive() { this.#user.active = false; return this; }
livingIn(city) { this.#user.address = { ...this.#user.address, city }; return this; }
build() { return structuredClone(this.#user); } // a fresh copy every time
}
const admin = new UserBuilder().withName("Asha").asAdmin().build();
const lockedUser = new UserBuilder().withEmail("locked@sqatools.in").inactive().build();
const mumbaiUser = new UserBuilder().livingIn("Mumbai").build();
console.log(admin);
console.log(lockedUser.active, lockedUser.role);
console.log(mumbaiUser.address);
⌨️ Terminal
node builder.js
🖥️ Output
{
name: 'Asha',
email: 'user@sqatools.in',
role: 'admin',
active: true,
address: { city: 'Pune', country: 'IN' }
}
false viewer
{ city: 'Mumbai', country: 'IN' }
💡 Tip: Read the test: new UserBuilder().inactive().build() says exactly what this test is about (an inactive user). Compare that with a 10-line object literal where the important field is buried among defaults.
📣 Observer and Publish/Subscribe
In the observer pattern, an object (the subject) keeps a list of listeners and notifies them when something happens. The subject does not know what listeners do, so you can add reporters, loggers or screenshots without touching the test runner. Node.js has it built in as EventEmitter; DOM events and Playwright’s page.on("console") are the same idea:
📄 observer.js
const { EventEmitter } = require("node:events");
class TestRunner extends EventEmitter {
async run(tests) {
this.emit("start", tests.length);
for (const t of tests) {
try { await t.fn(); this.emit("pass", t.name); }
catch (e) { this.emit("fail", t.name, e.message); }
}
this.emit("end");
}
}
const runner = new TestRunner();
// observers: each one is independent
const stats = { pass: 0, fail: 0 };
runner.on("pass", () => stats.pass++);
runner.on("fail", () => stats.fail++);
runner.on("start", (n) => console.log(`running ${n} tests`));
runner.on("fail", (name, msg) => console.log(`✗ ${name}: ${msg}`));
runner.on("end", () => console.log(`done: ${stats.pass} passed, ${stats.fail} failed`));
runner.once("fail", () => console.log("(first failure: a screenshot would be taken here)"));
runner.run([
{ name: "login", fn: () => {} },
{ name: "cart", fn: () => { throw new Error("total was 999, expected 998"); } },
{ name: "search", fn: async () => {} },
{ name: "pay", fn: async () => { throw new Error("timeout"); } },
]);
⌨️ Terminal
node observer.js
🖥️ Output
running 4 tests
✗ cart: total was 999, expected 998
(first failure: a screenshot would be taken here)
✗ pay: timeout
done: 2 passed, 2 failed
Playwright’s custom reporters work exactly like this: the runner calls onTestBegin, onTestEnd and onEnd on every registered reporter.
♟️ Strategy
The strategy pattern swaps an algorithm at runtime by passing it in. In JavaScript a strategy is usually just a function or an object of functions:
📄 strategy.mjs
const loginStrategies = {
ui: async (user) => `UI: typed ${user} into the login form`,
api: async (user) => `API: POST /api/login for ${user}, cookie stored`,
storageState: async (user) => `storageState: loaded .auth/${user}.json`,
};
async function login(user, strategy = "api") {
const fn = loginStrategies[strategy];
if (!fn) throw new Error(`unknown login strategy ${strategy}`);
return fn(user);
}
console.log(await login("asha", "ui")); // the one test that checks the login page
console.log(await login("asha")); // fast default for everything else
console.log(await login("asha", "storageState"));
// strategies for comparing values
const comparators = {
exact: (a, b) => a === b,
ignoreCase: (a, b) => a.toLowerCase() === b.toLowerCase(),
ignoreSpaces: (a, b) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim(),
normalised: (a, b) => comparators.ignoreSpaces(a.toLowerCase(), b.toLowerCase()), // combine both
};
for (const [name, cmp] of Object.entries(comparators)) console.log(name, cmp("Order Placed ", "order placed"));
⌨️ Terminal
node strategy.mjs
🖥️ Output
UI: typed asha into the login form
API: POST /api/login for asha, cookie stored
storageState: loaded .auth/asha.json
exact false
ignoreCase false
ignoreSpaces false
normalised true
🎁 Decorator
A decorator wraps a function (or object) to add behaviour without changing it: logging, timing, caching, retries. Higher-order functions make this natural in JavaScript:
📄 decorator.mjs
const withRetry = (fn, { retries = 2, delayMs = 10 } = {}) => async (...args) => {
for (let attempt = 1; ; attempt++) {
try {
return await fn(...args);
} catch (e) {
if (attempt > retries) throw new Error(`failed after ${attempt} attempts: ${e.message}`);
console.log(` attempt ${attempt} failed (${e.message}), retrying...`);
await new Promise((r) => setTimeout(r, delayMs));
}
}
};
const withLogging = (name, fn) => async (...args) => {
console.log(`→ ${name}(${args.join(", ")})`);
const result = await fn(...args);
console.log(`← ${name} returned ${JSON.stringify(result)}`);
return result;
};
// an unreliable API call: fails twice, then works
let calls = 0;
async function getOrderStatus(id) {
calls++;
if (calls < 3) throw new Error("503 Service Unavailable");
return { id, status: "shipped" };
}
const robustGetStatus = withLogging("getOrderStatus", withRetry(getOrderStatus));
await robustGetStatus(4521);
const neverWorks = withRetry(async () => { throw new Error("500"); }, { retries: 1 });
await neverWorks().catch((e) => console.log(e.message));
⌨️ Terminal
node decorator.mjs
🖥️ Output
→ getOrderStatus(4521)
attempt 1 failed (503 Service Unavailable), retrying...
attempt 2 failed (503 Service Unavailable), retrying...
← getOrderStatus returned {"id":4521,"status":"shipped"}
attempt 1 failed (500), retrying...
failed after 2 attempts: 500
⚠️ Watch out: Retry decorators are right for genuinely unreliable infrastructure (network blips, eventually consistent APIs). Wrapping assertions in retries to make flaky tests pass hides real bugs. Fix the cause, or use web-first assertions that wait for a condition.
🔌 Adapter
An adapter gives an existing object the interface your code expects, like a travel plug adapter. It lets tests use one interface over different libraries or API versions:
📄 adapter.js
// two services with different shapes
const legacyApi = { fetchUser: (id) => ({ user_id: id, full_name: "Asha Rao", is_active: 1 }) };
const newApi = { getUser: (id) => ({ id, name: { first: "Asha", last: "Rao" }, status: "ACTIVE" }) };
// adapters convert both to the shape the tests use
const fromLegacy = (api) => ({ getUser: (id) => { const u = api.fetchUser(id); return { id: u.user_id, name: u.full_name, active: u.is_active === 1 }; } });
const fromNew = (api) => ({ getUser: (id) => { const u = api.getUser(id); return { id: u.id, name: `${u.name.first} ${u.name.last}`, active: u.status === "ACTIVE" }; } });
// the same assertion code works for both versions
for (const [label, client] of [["legacy", fromLegacy(legacyApi)], ["v2", fromNew(newApi)]]) {
const user = client.getUser(7);
console.log(label, JSON.stringify(user), user.name === "Asha Rao" && user.active ? "✓" : "✗");
}
⌨️ Terminal
node adapter.js
🖥️ Output
legacy {"id":7,"name":"Asha Rao","active":true} ✓
v2 {"id":7,"name":"Asha Rao","active":true} ✓
🧪 Tester Scenario: The Page Object Model as a Pattern
The Page Object Model (POM) is the best-known testing pattern: one class per page or component, holding its locators and actions, so tests read like user stories and a UI change is fixed in one place. It combines encapsulation (module), and often factories and builders for data. Here it runs against a fake page object so the pattern is visible without a browser:
📄 pom.mjs
// a tiny fake "page" standing in for Playwright's page object
const fakePage = {
fields: {},
message: "",
async fill(selector, value) { this.fields[selector] = value; },
async click(selector) {
if (selector === "#sign-in") this.message = this.fields["#password"] === "Test#123" ? "Welcome, qa_user" : "Invalid credentials";
},
async textOf() { return this.message; },
};
class LoginPage {
constructor(page) {
this.page = page;
this.username = "#username"; // locators live in ONE place
this.password = "#password";
this.submit = "#sign-in";
}
async login(user, pass) {
await this.page.fill(this.username, user);
await this.page.fill(this.password, pass);
await this.page.click(this.submit);
return this.page.textOf("#message");
}
}
const loginPage = new LoginPage(fakePage);
console.log(await loginPage.login("qa_user", "wrong"));
console.log(await loginPage.login("qa_user", "Test#123"));
⌨️ Terminal
node pom.mjs
🖥️ Output
Invalid credentials
Welcome, qa_user
📄 pages/LoginPage.js (Playwright)
// the same page object with Playwright
export class LoginPage {
constructor(page) {
this.page = page;
this.username = page.getByLabel("Username");
this.password = page.getByLabel("Password");
this.submit = page.getByRole("button", { name: "Sign in" });
this.message = page.getByRole("status");
}
async login(user, pass) {
await this.username.fill(user);
await this.password.fill(pass);
await this.submit.click();
}
}
- Keep assertions in tests (or clearly named
expect...methods), not hidden inside actions. - Return data or other page objects from actions; avoid exposing raw selectors to tests.
- Do not over-engineer: a page with two buttons does not need a base class hierarchy.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write a factory createBrowserConfig(name) that returns viewport settings for “desktop”, “tablet” or “mobile” and throws for anything else.
Show answer
📄 practice1.js
const presets = { desktop: { width: 1280, height: 720 }, tablet: { width: 768, height: 1024 }, mobile: { width: 375, height: 812, isMobile: true } };
function createBrowserConfig(name) {
if (!presets[name]) throw new Error(`unknown device ${name}`);
return { name, ...presets[name] };
}
console.log(createBrowserConfig("mobile"));
try { createBrowserConfig("tv"); } catch (e) { console.log(e.message); }🖥️ Output
{ name: 'mobile', width: 375, height: 812, isMobile: true }
unknown device tvQ2. Create a ProductBuilder with defaults and methods withPrice(p) and outOfStock().
Show answer
📄 practice2.js
class ProductBuilder {
#p = { name: "Mouse", price: 799, stock: 10 };
withPrice(price) { this.#p.price = price; return this; }
outOfStock() { this.#p.stock = 0; return this; }
build() { return { ...this.#p }; }
}
console.log(new ProductBuilder().withPrice(0).outOfStock().build());🖥️ Output
{ name: 'Mouse', price: 0, stock: 0 }Q3. Use EventEmitter to emit an “order” event and have two listeners: one logs the id, one counts orders.
Show answer
📄 practice3.js
const { EventEmitter } = require("node:events");
const shop = new EventEmitter();
let count = 0;
shop.on("order", (id) => console.log("order", id));
shop.on("order", () => count++);
shop.emit("order", 101);
shop.emit("order", 102);
console.log("orders:", count);🖥️ Output
order 101
order 102
orders: 2Q4. Write a decorator withTiming(fn) that logs whether a function took less than 1 second.
Show answer
📄 practice4.mjs
const withTiming = (fn) => async (...args) => {
const start = performance.now();
const result = await fn(...args);
console.log(`${fn.name} under 1 s:`, performance.now() - start < 1000);
return result;
};
const loadReport = async () => "report ready";
console.log(await withTiming(loadReport)());🖥️ Output
loadReport under 1 s: true
report readyQ5. Pick a sorting strategy by name (“price”, “name”) and sort a copy of a product list with it.
Show answer
📄 practice5.js
const sorters = { price: (a, b) => a.price - b.price, name: (a, b) => a.name.localeCompare(b.name) };
const products = [{ name: "Mouse", price: 799 }, { name: "Cable", price: 499 }, { name: "Keyboard", price: 1499 }];
console.log(products.toSorted(sorters.price).map((p) => p.name));
console.log(products.toSorted(sorters.name).map((p) => p.name));🖥️ Output
[ 'Cable', 'Mouse', 'Keyboard' ]
[ 'Cable', 'Keyboard', 'Mouse' ]Q6. Which pattern would you use for each: (a) one place to read environment settings, (b) readable test users with defaults, (c) a Slack notifier that reacts to test failures, (d) wrapping a flaky network call?
Show answer
(a) Singleton (a config module). (b) Builder (or a factory with overrides). (c) Observer, listening to the runner’s failure events, like a custom reporter. (d) Decorator, a retry wrapper around the call, used only for genuinely unreliable infrastructure.
🧠 MCQ Quiz: Design Patterns
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which family does the Builder pattern belong to?Answer: Creational. It is about constructing objects.
- Why is an exported object from an ES module effectively a singleton?Answer: Modules are evaluated once and cached. Every importer gets the same instance.
- What does a factory do?Answer: Creates objects, choosing the concrete type for the caller. Callers do not need to know the class.
- What is the main benefit of a test-data builder?Answer: Tests state only the fields that matter, with defaults for the rest. It makes intent obvious.
- Which Node.js class implements the observer pattern?Answer: EventEmitter. on, once, emit and off.
- In the strategy pattern, what changes at runtime?Answer: The algorithm being used. Often just a function passed in.
- What does a decorator do?Answer: Adds behaviour by wrapping a function or object without changing it. Logging, caching, retries, timing.
- When is an adapter useful?Answer: When two components have incompatible interfaces. It translates one interface to another.
- Where should locators live in the Page Object Model?Answer: In the page object, defined once. A UI change is then fixed in one place.
- What is a risk of overusing singletons in tests?Answer: Shared mutable state makes tests order-dependent. Keep them read-only or reset them.
💼 Interview Questions and Answers
Q1. Which design patterns have you used in a test automation framework?
Page Object Model for pages and components; Factory to create browsers, API clients or reporters per environment; Builder (or object mother) for test data; Singleton for configuration; Observer for reporters and event hooks; Strategy for interchangeable login or comparison approaches; Decorator for logging, timing and retrying unreliable infrastructure calls; and Adapter to keep tests stable across API versions or libraries.
Q2. What is the difference between the observer and publish/subscribe patterns?
In observer, listeners subscribe directly to the subject that emits events (an EventEmitter, a DOM element). In publish/subscribe, publishers and subscribers do not know each other; messages go through a broker or channel (a message bus, Redis, Kafka), which decouples them further and can work across processes.
Q3. Factory vs Builder?
A factory creates a complete object in one call, typically choosing which type to create based on input. A builder assembles one complex object step by step through chained methods and is ideal when objects have many optional fields, such as test data where each test sets only what it cares about.
Q4. What are the pros and cons of the Page Object Model?
Pros: locators and flows live in one place, tests read like user stories, and UI changes require one fix. Cons: it can grow into huge “god” classes, hide assertions, or create deep inheritance trees; it adds indirection for tiny suites. Keep page objects small (per component), keep assertions visible, and prefer composition over inheritance.
❓ Frequently Asked Questions
🤔 Do I need classes to use design patterns in JavaScript?
No. Many patterns are simplest with functions, closures and plain objects: a factory is a function, a decorator is a higher-order function, a strategy is a function passed as an argument.
🤔 What is the “Screenplay” pattern?
An alternative to page objects in which actors perform tasks and ask questions. It scales well for very large suites but is more abstract; POM is still the most common in Playwright projects.
🤔 What is an anti-pattern?
A common solution that looks reasonable but causes problems, for example hard-coded sleeps, tests depending on each other, giant page objects, or retries used to hide flaky tests.
🤔 Where can I learn more patterns?
Refactoring.Guru has clear illustrated explanations, and Addy Osmani’s free book “Learning JavaScript Design Patterns” covers them in JavaScript.
🏁 Summary
- Patterns are named, reusable solutions: creational, structural and behavioural.
- Modules give encapsulation and singletons for free; keep singletons read-only in tests.
- Factories choose what to create; builders create readable test data with defaults.
- Observer (EventEmitter, reporters) decouples events from reactions; strategy swaps algorithms; decorator wraps behaviour; adapter bridges interfaces.
- The Page Object Model keeps locators and flows in one place; avoid over-engineering.
Next, continue with Lesson 68: Debounce, Throttle, Memoize.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in