Java Programming
Creational Design Patterns in Java: Singleton, Factory, Builder, Prototype
Intermediate8 min readUpdated
Creational patterns separate how objects are made from how they are used, which is what lets you swap implementations, enforce invariants and keep construction logic in one place. This guide explains Singleton, Factory Method, Abstract Factory, Builder and Prototype with idiomatic Java 21 code, shows where each appears in the JDK and Spring, and is candid about which are overused and what modern language features — enums, records, static factories, dependency injection — replace.
What you will learn
- Explain the problem each creational pattern solves and recognise it in the JDK and frameworks
- Implement a thread-safe Singleton correctly and know when a DI container should own it instead
- Use static factories and Factory Method to decouple callers from concrete classes
- Build immutable objects with many optional parameters using the Builder pattern
- Judge when a pattern adds clarity and when it adds ceremony
Design patterns are named solutions to recurring design problems. The names matter as much as the solutions: saying "make that a Builder" or "that is really an Abstract Factory" communicates a whole structure in three words. The five creational patterns from the original catalogue all attack one problem — code that does new ConcreteThing(...) is welded to that concrete class and to the details of constructing it — and they solve it in different situations. This guide covers each with Java 21 code and, just as importantly, notes where the language and frameworks have absorbed the pattern so that you no longer need to write it by hand.
Why construction needs patterns
A call to new commits three decisions at once: which class, what arguments, and when. Sometimes those decisions belong elsewhere — in configuration, in a subclass, in an object that knows the rules for building a valid instance. Three symptoms suggest a creational pattern:
- A class is instantiated in many places and you need to change which implementation is used, or add caching, pooling or logging around creation.
- A constructor has grown many parameters, most optional, and callers pass
nullor0for the ones they do not care about. - Creating an object requires steps, validation across fields or knowledge of other objects that the caller should not need.
The patterns below are the classic responses. Before them, one idiom deserves mention because it is the foundation for several: the static factory method (LocalDate.of, List.of, Executors.newFixedThreadPool). Unlike a constructor it has a descriptive name, can return a cached or pre-existing instance, can return a subtype or an interface, and can choose the class at run time. Many of the patterns are static factories with extra structure.
Singleton
Intent: guarantee that a class has exactly one instance and provide a global point of access to it.
The textbook implementation — private constructor, static instance, static getter — has been written badly so often that it deserves a precise treatment. On the JVM, the simplest correct forms are an enum or the initialisation-on-demand holder:
// Enum singleton: serialisation-safe, reflection-safe, thread-safe by the JLS
public enum ClockSource {
INSTANCE;
private final Clock clock = Clock.systemUTC();
public Instant now() { return clock.instant(); }
}
// Holder idiom: lazy, thread-safe without synchronisation, for classes that cannot be enums
public final class Registry {
private Registry() {}
private static final class Holder {
static final Registry INSTANCE = new Registry(); // initialised on first access to Holder
}
public static Registry get() { return Holder.INSTANCE; }
}
Both rely on the JVM's class-initialisation guarantee: a class is initialised exactly once, under a lock the JVM manages, and the result is visible to all threads. The infamous double-checked locking version — if (instance == null) synchronized (...) { if (instance == null) instance = new ...} — is correct only if the field is volatile, and even then it is more code to achieve what the holder idiom does with none.
The pattern's costs are what make it controversial. A Singleton fetched via Registry.get() inside a class is a hidden dependency: nothing in the class's constructor says it needs a Registry, tests cannot substitute one, and every test shares its state. The modern resolution is to keep the property — one instance — and drop the global access: let a dependency-injection container create the single instance and hand it to whoever declares a need for it. A Spring bean is singleton-scoped by default, which is why Spring applications rarely contain a getInstance() method. Reserve the hand-written pattern for code without a container and for truly process-wide resources such as a logging backend.
Factory Method
Intent: define an interface for creating an object, but let subclasses (or a supplied function) decide which class to instantiate.
The classic form is an abstract method in a superclass whose template logic calls it:
public abstract class ReportExporter {
public final Path export(Report report, Path dir) throws IOException {
Writer writer = createWriter(); // the factory method
Path target = dir.resolve(report.name() + "." + writer.extension());
Files.writeString(target, writer.render(report));
return target;
}
protected abstract Writer createWriter();
public interface Writer {
String extension();
String render(Report report);
}
}
public final class CsvExporter extends ReportExporter {
@Override protected Writer createWriter() { return new CsvWriter(); }
}
export is fixed; what it exports with is decided by the subclass. java.util.Calendar.getInstance(), NumberFormat.getInstance() and the Collection.iterator() method — each collection creating its own kind of iterator — are JDK examples.
Since Java 8, the subclass is often unnecessary: pass the creation as a Supplier<Writer> or Function<Config, Writer> in the constructor. That is the same pattern with a lambda in place of an override, and it composes better: you can build a Map<String, Supplier<Writer>> keyed by format name and look up the factory at run time, which is how plugin-style extension points are usually built. The JDK's ThreadFactory, Collectors.toCollection(ArrayList::new) and Stream.generate(supplier) all take factories this way.
A related simple form is the parameterised factory: one static method with a switch that returns a different implementation per argument. It is the right first step when there are few implementations and the caller knows which it wants by name; with a sealed interface the switch is exhaustiveness-checked.
Abstract Factory
Intent: provide an interface for creating families of related objects without naming their concrete classes.
Where Factory Method creates one product, Abstract Factory creates several that must be consistent with each other. The canonical example is a UI toolkit — buttons, menus and dialogs must all be from the same look-and-feel — and in backend code the same shape appears as a set of related infrastructure components:
public interface StorageFactory {
BlobStore blobs();
QueueClient queue();
LockProvider locks();
}
public final class AwsStorageFactory implements StorageFactory {
private final Region region;
public AwsStorageFactory(Region region) { this.region = region; }
@Override public BlobStore blobs() { return new S3BlobStore(region); }
@Override public QueueClient queue() { return new SqsQueueClient(region); }
@Override public LockProvider locks() { return new DynamoLockProvider(region); }
}
public final class LocalStorageFactory implements StorageFactory {
@Override public BlobStore blobs() { return new DirectoryBlobStore(Path.of("data")); }
@Override public QueueClient queue() { return new InMemoryQueue(); }
@Override public LockProvider locks() { return new FileLockProvider(); }
}
Application code receives a StorageFactory and never mentions S3 or the local directory. Swapping the whole family is one object. JDBC's DriverManager/Connection design is an abstract factory in spirit: a Connection creates Statements and PreparedStatements that match its database.
In a Spring application, profiles and @Configuration classes play this role — a @Profile("local") configuration defines the local family of beans, another defines the cloud family — so explicit factory interfaces appear mainly in libraries and framework-free code.
Builder
Intent: separate the construction of a complex object from its representation so the same process can produce different representations — in practice, provide a readable, step-by-step way to create an immutable object with many optional parts.
The Java form is a nested static class with fluent setters and a build() that validates and creates the immutable product:
public final class HttpRequestSpec {
private final URI uri;
private final String method;
private final Map<String, String> headers;
private final Duration timeout;
private final byte[] body;
private HttpRequestSpec(Builder b) {
this.uri = b.uri;
this.method = b.method;
this.headers = Map.copyOf(b.headers); // defensive, immutable
this.timeout = b.timeout;
this.body = b.body == null ? new byte[0] : b.body.clone();
}
public static Builder builder(URI uri) { return new Builder(uri); }
public static final class Builder {
private final URI uri; // required: constructor parameter
private String method = "GET"; // optional: sensible defaults
private final Map<String, String> headers = new LinkedHashMap<>();
private Duration timeout = Duration.ofSeconds(30);
private byte[] body;
private Builder(URI uri) { this.uri = Objects.requireNonNull(uri); }
public Builder method(String method) { this.method = method; return this; }
public Builder header(String name, String v) { headers.put(name, v); return this; }
public Builder timeout(Duration timeout) { this.timeout = timeout; return this; }
public Builder body(byte[] body) { this.body = body; return this; }
public HttpRequestSpec build() {
if (body != null && method.equals("GET")) {
throw new IllegalStateException("GET requests cannot carry a body"); // cross-field rule
}
return new HttpRequestSpec(this);
}
}
}
HttpRequestSpec spec = HttpRequestSpec.builder(URI.create("https://api.example.com/orders"))
.method("POST")
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.body(payload)
.build();
The call site names every value, the product is immutable, defaults live in one place and cross-field validation runs once in build(). The JDK uses this shape for HttpRequest.newBuilder(), ProcessBuilder, StringBuilder (a builder of strings) and Stream.Builder; Lombok's @Builder generates it, and records with many components often pair with a hand-written builder.
Two variants are worth knowing. A staged builder uses a chain of interfaces so that required steps must be called in order (.uri(...) returns a type that only offers .method(...)) — safer, more code. And a builder over a record can be as small as a mutable class whose build() calls the record's canonical constructor, keeping validation in the record's compact constructor.
Do not build a Builder for a type with two required fields; a constructor or record is clearer. The pattern pays for itself at four or more parameters or when optionality is real.
Prototype
Intent: create new objects by copying an existing instance rather than constructing from scratch.
Prototype matters when constructing an object is expensive (it loaded a large configuration, compiled a template, opened a connection pool) or when the caller wants "one like that, with a small change". Java's built-in mechanism is Object.clone() with the Cloneable marker interface, and it is widely regarded as a design mistake: clone() is protected on Object, performs a field-by-field shallow copy, skips constructors, and cannot assign final fields differently from the original. Prefer explicit copying:
public final class PipelineConfig {
private final List<String> stages;
private final Map<String, String> options;
public PipelineConfig(List<String> stages, Map<String, String> options) {
this.stages = List.copyOf(stages);
this.options = Map.copyOf(options);
}
public PipelineConfig(PipelineConfig other) { // copy constructor
this(other.stages, other.options);
}
public PipelineConfig withOption(String key, String value) { // "wither": copy with one change
Map<String, String> next = new HashMap<>(options);
next.put(key, value);
return new PipelineConfig(stages, next);
}
}
With immutable types the pattern becomes almost invisible: a "wither" method returns a modified copy and the original is untouched, which is safe to share across threads. Records make this idiomatic (new Config(existing.name(), newTimeout)), and a with-style syntax for records has been discussed for the language but is not in Java 21.
Where deep copies of mutable graphs are genuinely needed — a document model, a game state — a copy constructor per class that copies its children is more predictable than clone(), and serialising to and from bytes is a last resort that is slow and fragile.
Choosing between them
| Pattern | Use when | Modern substitute |
|---|---|---|
| Singleton | Exactly one instance of a process-wide resource, no container | DI container singleton scope; enum for constants-like objects |
| Factory Method | Subclasses or callers choose the concrete product | Supplier<T> / Function parameter; static factory with switch |
| Abstract Factory | Several products must come from one consistent family | Spring profiles and configuration classes |
| Builder | Many parameters, optional values, cross-field validation, immutability | Record + compact constructor for small all-required types |
| Prototype | Copy-with-changes or expensive construction | Copy constructors and withers on immutable types |
Common mistakes
Singleton as a global variable. Mutable static state reached from anywhere, untestable and racy. Inject it.
Broken lazy Singleton. Double-checked locking without volatile, or a plain unsynchronised null-check, creates two instances under load. Use an enum or the holder idiom.
Factory that only wraps new. ThingFactory.create() returning new Thing() with no variation point is ceremony. Add the pattern when there is a second implementation or a construction rule to centralise.
Mutable product after build(). A builder whose product still has setters loses the immutability that justified it.
Builder without validation. build() is the one place that sees all fields; check the cross-field invariants there.
clone() on classes with mutable fields. The shallow copy shares the mutable parts; both copies mutate each other's lists. Copy explicitly.
Reflection defeating a Singleton. A private constructor can be called through reflection; the enum form is the only one the JVM protects, and also the only one that survives serialisation as a single instance.
Key takeaways
- Creational patterns decouple code from concrete classes and centralise construction rules; the static factory method is the building block for most of them.
- Implement a Singleton as an enum or with the holder idiom, and prefer a DI container's singleton scope so that the dependency is visible and testable.
- Factory Method delegates the choice of product to a subclass or, in modern Java, to a
Supplier/Functionpassed in; Abstract Factory does the same for a family of products that must match. - Builder is the answer to many optional parameters: named values at the call site, immutability, one place for defaults and validation.
- Prototype in Java means copy constructors and withers on immutable types, not
Cloneable. - Apply a pattern when the variation it supports actually exists; a pattern with one implementation is indirection without benefit.
Sources and further reading
Frequently asked questions
- Is the Singleton pattern an anti-pattern?
- The hand-written global-access version usually is: it hides dependencies, makes tests share state and is hard to replace. The idea of one instance per application is fine and is exactly what a Spring singleton-scoped bean gives you, injected rather than fetched. Write a Singleton class only for genuinely process-wide resources in code that has no container.
- What is the difference between Factory Method and Abstract Factory?
- Factory Method is one overridable method that creates one product, letting subclasses decide the concrete class. Abstract Factory is an object whose methods create a family of related products that must be used together, such as the widgets of one look-and-feel or the drivers of one database. Abstract factories are often implemented with factory methods.
- When should I use a Builder instead of a constructor?
- When a type has more than three or four parameters, several of them optional, or when validation must consider several fields together. A builder keeps the result immutable, names every value at the call site and avoids the telescoping-constructor explosion. For a small value with all-required fields, a record's canonical constructor is simpler.
- Should I use clone() for the Prototype pattern?
- Prefer a copy constructor or a static copy method. Object.clone is protected, requires the Cloneable marker interface, performs a shallow copy by default and bypasses constructors, so invariants and final fields are awkward. A copy constructor is explicit, deep where you decide, and works with final fields.