Skip to the page

Design patterns · core

Factory, builder and singleton

A factory moves object creation out of business code. A builder makes objects with many optional fields readable and safe. A singleton means one instance, but a global getInstance is usually a problem; prefer one instance passed in.

The notes

What you must know

  • Factory: callers depend on the Channel interface and never call new SmsChannel with vendor config. A simple factory ChannelFactory.get(type) is better backed by a registry map than a switch.
  • Factory method: a base class defines a creation method that subclasses override. Abstract factory creates a family that must match, such as all real providers or all fake providers for tests.
  • Builder: telescoping constructors are unreadable and setters leave a half-built mutable object. A builder takes required fields up front, optional ones by name, and build() validates and returns an immutable object.
  • Do not use a builder for a two-field class. In Python use keyword arguments with defaults and a frozen dataclass; in TypeScript use an options object.
  • Singleton problems with a static getInstance: hidden global dependency, state that leaks between tests, fixed start order, no two instances, and lazy creation races.
  • Better: create one instance at startup and pass it in. Spring default singleton scope works this way.
  • If you must write one: an enum singleton or the holder-class idiom. Double-checked locking needs a volatile field, because without it another thread can see a partly built object.
  • A singleton can be broken by reflection, serialisation and multiple class loaders. In Node.js a module export is cached, so it acts as a singleton per process.

The red pen

Common traps: mistake → fix

  • Mistake: Singletons are always an anti-pattern

    Fix: the need for one pool is real; the static global access is the problem.

  • Mistake: Double-checked locking works without volatile

    Fix: it can expose a partly built object.

  • Mistake: A factory should also hold business logic

    Fix: it should only create.

  • Mistake: Abstract factory and factory method are the same

    Fix: one creates a family, the other is an overridable method.

Easy to hard

Questions interviewers ask, easy to hard

  1. Where does object creation go in a notification system with many channels?
  2. Factory method or abstract factory?
  3. When do you use a builder and when not?
  4. Is a singleton useful or harmful? How do you make one safely?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview