Creating objects

Singleton, factory, builder and prototype — and why Spring turned the first from a pattern into a scope.

9 min read📐 Low-Level Design

Four patterns about the same question: who decides how this object comes into existence, and what do they need to know to do it?

Three of them are worth knowing. One of them Spring has made almost irrelevant, and that is worth knowing too.

Singleton, and why Spring made it boring

One instance, shared. The textbook version is a class that hides its own constructor:

java
public class Registry {
    private static final Registry INSTANCE = new Registry();
    private Registry() {}
    public static Registry getInstance() { return INSTANCE; }
}

That works, and the reason it has a reputation is not the code — it is what the code does to everything around it:

  • It is global mutable state, with every problem global state has ever had.
  • It cannot be substituted in a test. A class calling Registry.getInstance() has a hard dependency nothing can replace.
  • Initialisation order and threading are subtle enough that "double-checked locking" is a famous bug rather than a technique.

Spring's answer removes all three: a bean is a singleton by default, created once by the container and injected wherever it is needed.

java
@Service
class Registry { }        // one instance, and every user declares its dependency

The instance is still shared and the sharing is now visible in constructors, which means a test passes a different one and nothing global exists. That is the whole improvement, and it is why singleton in a Spring application is not a pattern you implement — it is a scope you choose.

The enum singleton is still the best hand-written form when you need one — serialisation-safe and reflection-safe, which the private-constructor version is not:

java
public enum Registry { INSTANCE; }

Factory — when the caller should not know the class

A factory decides which implementation to return, so callers do not have to:

java
PaymentProcessor forMethod(String method) {
    switch (method) {
        case "card":  return new CardProcessor();
        case "upi":   return new UpiProcessor();
        default:      throw new IllegalArgumentException(method);
    }
}

Callers get a PaymentProcessor and never name a concrete class. Adding a method changes one place.

You have met static factories constantly, and they are the more common form in modern Java: List.of, Optional.of, Integer.valueOf, Instant.now. Their advantages over a constructor are worth stating because they explain why the JDK keeps adding them:

  • They have names. Duration.ofMinutes(5) against new Duration(5, MINUTES).
  • They need not return a new instance. Integer.valueOf returns a cached object for small values — the primitives lesson's == surprise is a factory doing its job.
  • They can return a subtype. List.of(1,2) returns a different class from List.of(1,2,3), and you never need to know.

In Spring, a @Bean method is a factory method, and the container is a factory. BeanFactory is not a coincidental name.

Builder — when a constructor has too many arguments

The problem it solves is telescoping constructors and, worse, this:

java
new Order(customerId, null, 5, true, null, false, 3);   // what is true?

A builder names the arguments and lets the object be immutable once built:

java
Order order = Order.builder()
    .customerId(id)
    .quantity(5)
    .expedited(true)
    .build();

Worth knowing about the real version: validate in build(), not in the setters. That is the only point where the object is complete, and it is where "expedited orders need an address" can be checked. A builder whose build() does nothing is a mutable object with extra steps.

Three or four parameters do not need a builder. Seven do, and so do any two adjacent parameters of the same type — new Range(start, end) is fine, new Rectangle(2, 3, 4, 5) is a bug waiting to be transposed.

Lombok's @Builder generates it; a record plus a builder is the common modern shape where your baseline allows records.

Prototype — copy an existing object

Create by copying rather than constructing, when construction is expensive or the configuration is easier to copy than to describe.

Java's built-in support for this is Cloneable and clone(), and the honest advice is: do not use it. Cloneable is a marker interface with no clone method on it, Object.clone is protected, the default is a shallow copy, and the interaction with final fields is broken. It is widely regarded as a design mistake in the library.

What to do instead:

java
// a copy constructor — explicit, and you control the depth
public Order(Order other) { this.customerId = other.customerId; ... }
 
// or a static factory that says what it does
static Order copyOf(Order other) { ... }

The pattern still appears where it earns its place: Spring's @Scope("prototype") means "a new instance per injection", which is the same idea at the container level, and a cached template object that requests copy and modify is a reasonable design.

But prototype is the lowest-value pattern in this lesson, and a copy constructor is almost always the better expression of it.

Under the hood: what new actually runs, in order

Every pattern above is a decision about who builds an object. The JVM has its own fixed answer to what happens once new runs, and it is worth knowing precisely, because two of the mistakes above — a singleton whose fields are read before they are set, a builder that validates in the wrong place — are really mistakes about this order.

new Sub(), where Sub extends Base, runs in a sequence fixed by the JLS and never reordered by a compiler or a framework:

  1. The JVM allocates the object and zeroes every field — 0, 0.0, false, null depending on type — before any constructor body has run at all. This is not a constructor call; it is what "allocate" means. A field with no initializer is not "uninitialized" in the sense C leaves memory uninitialized — it is guaranteed zero.
  2. The constructor's first action is super(...), explicit or implicit. If you write neither this(...) nor super(...) as the first statement, the compiler inserts a call to the no-arg superclass constructor for you. Base's constructor runs to completion — its own super call, its own field initializers, its own body — before Sub proceeds.
  3. Back in Sub, its instance variable initializers and instance initializer blocks run, in textual order, top to bottom, exactly as they appear in the source.
  4. The rest of the constructor body runs last.

That ordering is why a field initializer can safely call an instance method (int x = init();) and see it run after the superclass is fully constructed but before the rest of the constructor body — and why, going the other way, calling an overridable instance method from inside a superclass constructor is a well-known trap: at that point the subclass's own field initializers have not run yet, so the override sees fields still at their zeroed default.

When a constructor delegates with this(...) instead of super(...), step 2 above does not happen for that constructor — the delegated-to constructor runs the full chain (including step 3) exactly once, so field initializers never run twice no matter how many constructors in the chain call this(...).

Try it yourself

Predict the construction order

java
class Base {
    Base() { System.out.println("Base()"); }
}
class Sub extends Base {
    int x = init();
    Sub() {
        System.out.println("Sub() before x=" + x);
    }
    int init() { System.out.println("field init"); return 5; }
}
new Sub();

Walk the four-step order above before running it: when does Base() print relative to field init, and does x already have its real value by the time Sub()'s own println runs?

Why the superclass constructor always finishes before a subclass's field initializers run

Base() prints first because step 2 is unconditional: Sub's implicit super() call runs and completes before anything else in Sub happens, even before Sub's own fields are touched. field init prints second because step 3 — Sub's field initializers, in textual order — runs immediately after super() returns and strictly before the rest of the constructor body. By the time Sub()'s own println executes (step 4), x already holds 5, because it was assigned in step 3. Nothing here is a JVM implementation detail; it is specified order, the same on every conforming JVM.

Misconceptions

  • "A field with no initializer is uninitialized until the constructor body sets it." It is not — the JVM zeroes every field as part of allocation, before any constructor runs (step 1). "Uninitialized" in the C sense — garbage bytes — does not exist for a Java object field; the worst case is a field holding its correct-but-unhelpful default (0, null) a moment longer than you expect.
  • "A constructor can call both this(...) and super(...)." It cannot — the JLS requires that if either appears, it must be the constructor's first statement, which means at most one of them can appear at all. A constructor either delegates within the class or calls up to the superclass; never both.

Sources

  • Joshua Bloch, Effective Java (3rd ed.) — Item 1 (static factories), Item 2 (builders), Item 3 ("Enforce the singleton property with a private constructor or an enum type").
  • The Java Language Specification, §12.5 "Creation of New Class Instances" and §8.8.7 "Constructor Body" — the order of allocation, superclass construction, instance initializers and the constructor body.
Progress is saved on this device and to your account when signed in.