Skip to content

Creational Patterns — Notes#

Why#

  • Decouple "what to use" from "how to make it".
  • Centralise construction logic so it can be swapped, tested, mocked.

Singleton pitfalls#

  • Acts as global state.
  • Hard to test (must reset between tests).
  • Multi-threaded init needs care (double-checked locking, volatile, or eager init).
  • Frequently better: inject a single instance via the DI container.

Builder vs telescoping constructors#

  • 4 parameters? Reach for Builder.

  • Required vs optional: enforce required in Builder constructor; expose setters for optional.
  • Fluent (return this) reads better.

Modern alternatives#

  • Kotlin: data class + named/default args replaces Builder for many cases.
  • Java records (since 14) cover simple POJOs.
  • Python: keyword arguments + dataclasses replace most of Builder.
  • Go: functional options (WithTimeout(5), WithRetries(3)).

Refs#

  • Design Patterns: Elements of Reusable Object-Oriented Software — Gamma, Helm, Johnson, Vlissides (GoF, 1994).
  • Effective Java (Bloch) — Item 2 (Builder), Item 3 (Singleton).
  • Refactoring.guru patterns gallery.