Skip to content
Tutorials Center
My learning

Topics

Lesson 159 of 201 ยท JVM and Advanced Topics

Creational Design Patterns

Learn creational design patterns in Java - singleton (enum and lazy holder), static factories, factory method, abstract factory, builder and prototype - with runnable code.

A design pattern is a named, proven solution to a problem that keeps coming up in object-oriented code. The idea was popularized in 1994 by the book Design Patterns by Gamma, Helm, Johnson and Vlissides (the "Gang of Four", or GoF), which catalogued 23 patterns in three groups: creational (how objects are created), structural (how objects are composed) and behavioral (how objects interact). Patterns give teams a shared vocabulary: "make it a builder" says in three words what would otherwise take a paragraph.

This lesson covers the creational patterns. They all answer variations of one question: who decides which object gets created, and how? Calling new ConcreteClass(...) everywhere hard-wires that decision into every caller, which is exactly what the Dependency Inversion and Open/Closed principles warn against. You'll see each pattern in runnable, modern Java (records, enums, lambdas), along with the cases where the pattern is overkill.

Singleton

Intent: guarantee that a class has exactly one instance, and give everyone access to it.

Typical candidates are things that really are unique in a process: a configuration snapshot, a registry, a metrics collector. Java offers three good implementations; each relies on a guarantee from the JVM that you met in JVM Architecture: a class is initialized once, lazily and thread-safely.

Java
// 1. Eager: created when the class is initialized
public final class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();
    private AppConfig() {}                         // nobody else can call new
    public static AppConfig getInstance() { return INSTANCE; }
}

// 2. Lazy holder: created on the first getInstance() call
public final class Registry {
    private Registry() {}
    private static class Holder {
        static final Registry INSTANCE = new Registry();
    }
    public static Registry getInstance() { return Holder.INSTANCE; }
}

// 3. Enum: the JVM guarantees exactly one instance per constant
public enum Metrics {
    INSTANCE;
    private final Map<String, Long> counters = new ConcurrentHashMap<>();
    public void increment(String name) { counters.merge(name, 1L, Long::sum); }
}

The lazy holder idiom works because the nested Holder class isn't initialized until getInstance() first touches Holder.INSTANCE. No synchronized, no volatile, no cost after the first call. The enum version is the most robust: it's automatically serializable without creating a second copy on deserialization, and reflection can't create another instance. Let's verify both claims:

Java Lazy holder and enum singletons under pressure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The constructor message appears when getInstance() is first called, not when the unrelated static method runs. All 8 threads see the same object, and the counter reaches exactly 8,000. A determined caller can still use reflection to call a private constructor of a normal class, but the JVM refuses to create extra enum constants.

You may also meet double-checked locking, an older lazy idiom. It's only correct if the field is volatile; without it, another thread can see a partially constructed object:

Java
private static volatile Connection instance;      // volatile is essential
static Connection getInstance() {
    Connection local = instance;
    if (local == null) {
        synchronized (Connection.class) {
            local = instance;
            if (local == null) {
                instance = local = new Connection();
            }
        }
    }
    return local;
}

Prefer the holder idiom; it's shorter and impossible to get wrong.

Singletons are global state in disguise. Code that calls Registry.getInstance() deep inside a method has a hidden dependency: you can't see it in the constructor, and you can't replace it in a test. In applications, it's usually better to create one instance at startup and pass it to whoever needs it (dependency injection). Spring beans are singletons by default in exactly this sense: one per container, injected, never fetched from a static method.

Static factory methods

Before the GoF factories, here's the simplest creational technique, and the one you'll use most: a static method that returns an instance, instead of a public constructor. The JDK is full of them:

Java
List<String> list = List.of("a", "b");          // returns a hidden, optimized implementation
Integer cached = Integer.valueOf(42);           // may return a cached instance
LocalDate date = LocalDate.of(2026, 3, 14);     // validates the arguments
Path path = Path.of("data", "report.csv");
var formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
Optional<String> empty = Optional.empty();      // always the same shared instance

Compared with constructors, static factories can:

  • have descriptive names: Duration.ofMinutes(5) vs a mysterious new Duration(300, 0);
  • return cached or shared instances instead of always allocating;
  • return any subtype, even a private class, so the implementation can change freely (List.of returns different classes for 0, 1, 2 or more elements);
  • choose the subtype based on the arguments.

Common naming conventions: of (aggregates parameters), from (converts one value), valueOf, parse, getInstance/newInstance, create, and newXxx/xxx for a different type (Files.newBufferedReader, Collections.list).

Factory Method

Intent: define an interface for creating an object, but let subclasses (or a supplied function) decide which class to instantiate.

In the GoF form, a base class contains an algorithm that needs some object, and calls an abstract "factory method" to get it. Each subclass overrides only that method. It's the template method idea applied to creation:

Java Factory method: subclasses choose the product

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In modern Java, you often don't need the subclass at all: a Supplier<RowWriter> (or any functional interface) is a factory, and a constructor reference like CsvWriter::new is the most compact factory method there is.

A related everyday idiom is a factory that picks an implementation from input, sometimes called a simple factory:

Java
static RowWriter writerFor(String fileName) {
    return switch (fileName.substring(fileName.lastIndexOf('.') + 1)) {
        case "csv" -> new CsvWriter();
        case "md"  -> new MarkdownWriter();
        default    -> throw new IllegalArgumentException("Unsupported format: " + fileName);
    };
}

Callers depend only on RowWriter, and the one switch lives in one place.

Abstract Factory

Intent: create families of related objects without naming their concrete classes, so that objects from one family are always used together.

Imagine a UI library with light and dark themes. A dark button must never be combined with a light dialog. An abstract factory has one creation method per product, and each concrete factory produces a matching family. The same shape shows up with database dialects (connection, SQL builder and type mapper per database), cloud providers (storage, queue and key vault per vendor) and test doubles (a "fake" family of all services).

Java Abstract factory: consistent families of UI widgets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The theme is chosen in exactly one place, and showDeleteConfirmation can't accidentally mix families. The cost: adding a new product (say, a Checkbox) means changing the factory interface and every family. Abstract factory fits when families are stable and new families are what you add. The JDK's javax.xml.parsers.DocumentBuilderFactory and java.sql.Connection (which creates matching Statements and Blobs for its driver) follow this pattern.

Builder

Intent: construct a complex object step by step, separating how it's assembled from its final, often immutable, representation.

Builders solve the telescoping constructor problem. With many optional parameters you end up with constructors like new Email("[email protected]", "Hi", "Body", null, null, true, false, 3), where nobody can tell which argument is which, and adding a field breaks every caller. A builder gives each value a name, provides defaults, validates everything once in build(), and produces an immutable object:

Java A builder with validation and an immutable result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Design points worth copying:

  • The target class has a private constructor taking the builder, so half-built objects can't exist.
  • Required values go into the builder's entry point (Email.to(...)), optional ones get defaults.
  • Each setter returns this for chaining, a "fluent" API (see The this Keyword).
  • Validation that involves several fields happens once in build().

The JDK uses builders where objects have many options: HttpRequest.newBuilder(), HttpClient.newBuilder(), Thread.ofVirtual().name("worker-", 0).factory(), Locale.Builder, Stream.builder() and, of course, StringBuilder. Libraries such as Lombok (@Builder) and record-builder generators write the boilerplate for you.

For a record with only a few fields, you usually don't need a builder: a compact constructor validates, and "wither" methods give a fluent way to make modified copies:

Java
record Pizza(String size, List<String> toppings, boolean extraCheese) {
    Pizza {
        toppings = List.copyOf(toppings);
    }
    Pizza withExtraCheese() { return new Pizza(size, toppings, true); }
}

Prototype

Intent: create new objects by copying an existing, preconfigured instance (the prototype), instead of building each one from scratch.

Prototype helps when objects are expensive or complicated to configure, and you need many similar ones: game entities, document templates, preconfigured requests, test fixtures. Each prototype knows how to copy itself; a registry hands out copies, which callers then adjust. Java's built-in Cloneable/clone() was intended for this, but it is awkward and error-prone (see Copying Objects). A plain copy() method built on a copy constructor is the modern way:

Java Prototype: a registry of preconfigured templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The "expensive setup" line prints only twice, once per prototype, no matter how many enemies are spawned, and changing the boss's ability list doesn't affect the stored troll because copy() makes a deep copy of the mutable list. Forgetting that (copying only the reference) is the classic prototype bug: every copy would share one list. Immutable fields like String and records can be shared safely.

Choosing a creational pattern

Problem Pattern
Exactly one instance per process, accessed widely Singleton (enum or lazy holder), but prefer injecting one instance
A readable name, caching, or hiding the concrete class Static factory method
An algorithm needs an object, and the variant should decide which Factory method (or a Supplier parameter)
Families of related objects that must match Abstract factory
Many optional parameters, validation across fields, immutability Builder
Many similar objects that are costly to configure from scratch Prototype (copy() methods, not clone())

Patterns are tools, not goals. A class with two fields doesn't need a builder, and a single implementation doesn't need a factory. Reach for a pattern when you feel the pain it solves, and name it in your code (EmailBuilder, WidgetFactory) so readers recognize it instantly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the lazy holder singleton thread-safe without synchronized?

    Class initialization is performed once under a JVM lock, and Holder is only initialized when getInstance first reads Holder.INSTANCE.
  2. 2. What does a typical builder's build() method do that individual setter methods don't?

    Setters only record values. build() checks cross-field rules once and calls the target's private constructor, so invalid objects never exist.
  3. 3. A prototype's copy() assigns this.tags = source.tags; where tags is an ArrayList. What happens when one copy adds a tag?

    That is a shallow copy. All objects share the same list, so changes leak. Copy mutable fields with new ArrayList<>(source.tags).
  4. 4. You need dark-theme and light-theme widgets and must never mix a dark button with a light dialog. Which pattern fits best?

    An abstract factory creates whole families of related products, so each concrete factory only produces widgets of one theme.
  5. 5. Which is NOT an advantage of static factory methods like List.of over public constructors?

    Classes with only static factories and private constructors can't be subclassed, which is a limitation (often a welcome one), not an advantage.

Summary

  • Creational patterns decide who creates objects and which class is used, so callers don't hard-wire new ConcreteClass().
  • Singleton: use an enum or the lazy holder idiom (double-checked locking needs volatile); prefer injecting one instance over global access.
  • Static factory methods (of, from, valueOf) give names, caching and hidden implementations.
  • Factory method: a base algorithm delegates creation to subclasses; in modern Java, a Supplier or constructor reference often replaces the subclass.
  • Abstract factory: one factory per family of related products keeps families consistent.
  • Builder: named, optional, validated parameters and an immutable result; small records rarely need one.
  • Prototype: copy preconfigured instances with copy() and copy constructors, deep-copying mutable fields.

Next: Structural and Behavioral Design Patterns, where you'll combine objects with adapters, decorators and proxies, and coordinate them with strategies, observers and state machines.