Creational patterns: Factory, Builder, Singleton

Ways to create objects without hard-wiring the exact class: factories, builders, prototypes and why Singleton is usually a last resort.

On the roadmap:Software Design · step 2: Design patterns

Lesson 3 of 7 · 9 min read · quiz · exercise

The goal

Creational patterns manage how objects are created, so the rest of the code does not depend on exact classes or messy construction steps.

Factory Method (and simple factories)

Callers ask for what they need, and a factory decides which concrete class to create.

interface Sender { send(to: string, text: string): Promise<void> }

class EmailSender implements Sender { async send(to: string, text: string) { /* ... */ } }
class SmsSender   implements Sender { async send(to: string, text: string) { /* ... */ } }

function createSender(channel: "email" | "sms"): Sender {
  switch (channel) {
    case "email": return new EmailSender();
    case "sms":   return new SmsSender();
  }
}

await createSender(user.preferredChannel).send(user.contact, "Your code is 482913");

Benefits: one place to change when classes change, callers depend only on the interface, and tests can supply fakes. A registry (a map from name to constructor) makes adding a type a one-line change.

Factory Method as a picture

Figure SDA-SDE-03-1 · Calling code, factory and products · © forcsguy.com

Abstract Factory

Create families of related objects that must be used together, such as a UI toolkit's button, checkbox and menu for one platform or theme.

interface UiFactory { button(): Button; checkbox(): Checkbox }
class DarkUi implements UiFactory { /* returns dark variants */ }
class LightUi implements UiFactory { /* returns light variants */ }

Use it when several products must stay consistent. Skip it when you only vary one object.

Builder

Construct a complex object step by step, especially with many optional parts. In languages with named parameters or option objects this is often just that.

const request = new RequestBuilder("https://api.example.com/orders")
  .method("POST")
  .header("Authorization", token)
  .json({ items })
  .timeout(5000)
  .build();   // validates and returns an immutable Request

Benefits: readable construction, validation in one place, and immutable results. The alternative, a constructor with ten positional parameters, is easy to misuse.

Prototype

Create new objects by copying an existing one, useful when creation is expensive or when you want variations of a configured template.

const base = { retries: 3, timeout: 2000, headers: { accept: "json" } };
const slow = { ...base, timeout: 10000 };            // shallow copy with a change
const deep = structuredClone(base);                  // deep copy

Beware shallow versus deep copies: sharing nested objects causes surprising bugs.

Singleton

Ensures only one instance exists and gives global access to it.

class Config {
  private static instance?: Config;
  static get(): Config { return (Config.instance ??= new Config()); }
}

It looks convenient but has real costs: hidden dependencies, global mutable state, difficulty in testing (state leaks between tests), and trouble with concurrency. Often what you really need is one instance, not global access.

Better: create the single instance once, in the application's start-up code (the composition root), and inject it into what needs it. You keep "only one" without making it global.

Choosing

SituationPattern
Which class to create depends on input or configurationFactory Method or a registry
Several related objects must matchAbstract Factory
Many optional parts, validation neededBuilder or an options object
Cloning a configured templatePrototype or a copy
"There should be only one"Create one in the composition root and inject it

Prefer the lightest form your language offers: a function that returns an object is often all the "factory" you need.

Real-world reading

Check your understanding

Question 1 of 3

0 correct so far

When is a Builder useful?

Go deeper

© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.