Skip to content

Creational Patterns Deep Dive

Master Singleton, Factory Method, Abstract Factory, Builder, and Prototype patterns.

What you'll learn

  • Singleton: one instance, global access
  • Factory Method: defer instantiation to subclasses
  • Builder: construct complex objects step by step
  • Prototype: clone existing objects

Concept

Creational Patterns Deep Dive

Creational patterns abstract the object creation process, making a system independent of how its objects are created, composed, and represented.

Singleton

Ensures a class has exactly one instance and provides a global access point. Use for: configuration managers, connection pools, loggers. Warning: Singleton is the most over-used and abused pattern. It introduces global state, makes testing hard, and hides dependencies. Prefer dependency injection when possible.

Factory Method

Defines an interface for creating an object but lets subclasses decide which class to instantiate. The creator class does not know the exact product class - it works through a common interface. This is useful when a class cannot anticipate the type of objects it must create.

Abstract Factory

Creates families of related objects without specifying their concrete classes. Example: a UI toolkit factory that creates Button, TextField, and Dialog - MacFactory creates Mac-styled widgets, WindowsFactory creates Windows-styled ones.

Builder

Separates construction of a complex object from its representation. Instead of a constructor with 10 parameters, you chain methods: new Pizza().size(L).crust(thin).toppings([cheese, olives]).build(). This handles optional parameters elegantly and produces immutable objects.

Prototype

Creates new objects by cloning a prototype instance. Useful when creating a new object is expensive. JavaScript Object.create() and the spread operator are prototype-based cloning.

Example

              // Builder pattern: constructing a complex object
class HttpRequest { constructor() { this.method = 'GET'; this.url = ''; this.headers = {}; this.body = null; } }
class HttpRequestBuilder {
  constructor() { this.req = new HttpRequest(); }
  method(m) { this.req.method = m; return this; }
  url(u) { this.req.url = u; return this; }
  header(k, v) { this.req.headers[k] = v; return this; }
  body(b) { this.req.body = b; return this; }
  build() { return this.req; }
}
// Prototype: clone via spread
const template = { retries: 3, timeout: 5000, headers: {'Content-Type': 'application/json'} };
const apiConfig = {...template, headers: {...template.headers, 'Authorization': 'Bearer token'}};
// Factory Method
class AnimalFactory {
  static create(type) {
    if (type === 'dog') return {speak: () => 'Woof'};
    if (type === 'cat') return {speak: () => 'Meow'};
    throw new Error('Unknown animal');
  }
}
const req = new HttpRequestBuilder().method('POST').url('/api/users').header('Auth', 'token').body({name: 'Ada'}).build();
console.log(req.method, req.url, req.body);
console.log(apiConfig.retries, apiConfig.headers.Authorization);
console.log(AnimalFactory.create('dog').speak());
            

The Builder chains methods that return this, enabling fluent construction. The Prototype uses spread to clone with overrides. The Factory Method centralizes object creation logic.

Try it

  • JSON Formatter

    Builder patterns often produce JSON objects - see the constructed structure.

Common mistakes

The mistake

Making the Singleton constructor public.

The fix

The constructor must be private/protected to prevent external instantiation. In JS, use a module-scoped variable and export only a getInstance() function.

The mistake

Creating a Builder for simple objects with 2-3 fields.

The fix

Builder adds a class and chain methods. For simple objects, use a plain constructor or object literal. Builder pays off only for many optional fields.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors