Every object has to be created somewhere. In small programs that is a plain new. In larger programs, new spread everywhere causes three problems: code is tied to one concrete class, constructors take too many arguments, and nobody controls how many instances exist. Creational patterns solve these. This lesson covers the three that interviewers ask about most: Factory, Builder and Singleton. Every example below is real, tested code: an alert and notification service that sends SMS and email, and runs on AWS or Google Cloud.
1. Why Creation Needs a Pattern
| Pattern | Problem it solves | Idea | In the JDK |
|---|---|---|---|
| Factory | The caller should depend on an interface, not on the concrete class behind it | A method picks the class and returns an interface | List.of, Calendar.getInstance |
| Builder | Many fields, some optional, and the object must be valid | Set fields step by step, then check and build once | StringBuilder, HttpRequest.newBuilder |
| Singleton | Exactly one instance is needed | Hide the constructor and hand out one shared object | Runtime.getRuntime |
There are two more creational patterns. Prototype builds new objects by copying a ready-made one. It is useful for templates, such as a report that always starts with the same title, sections and styling. The copy must be deep: new list, new nested objects, otherwise two reports share the same data. Object pool reuses expensive objects, such as database connections (the connection pooling lesson covers this). Both are asked less often, so learn the three in the table first.
2. Factory
The Factory pattern solves tight coupling between client code and concrete classes when creating objects. The word "factory" covers three different things. Say which one you mean.
2.1 Simple (Static) Factory
One method holds the new calls and picks the class from an input. List.of(...), Optional.of(...) and LocalDate.of(...) are static factory methods. They have clear names and can return a cached object or a subtype. It is the simplest form and the one to reach for first. The next two forms have full examples.
2.2 Factory Method
This is the pattern from the original Gang of Four book. A base class owns a workflow and has one step that creates the object. Subclasses decide which class to create. The base class uses the result without knowing what it is.
First the product: an interface and two implementations.
interface Channel {
void send();
}
final class Sms implements Channel {
@Override
public void send() {
System.out.println("SMS Sent !!!");
}
}
final class Email implements Channel {
@Override
public void send() {
System.out.println("Email Sent !!!");
}
}
Now the creator. sendMessage() is the workflow. createChannel() is the factory method that subclasses fill in.
abstract class NotificationService {
protected abstract Channel createChannel();
public void sendMessage() {
Channel channel = createChannel();
channel.send();
}
}
final class SmsNotificationService extends NotificationService {
@Override
protected Channel createChannel() {
return new Sms();
}
}
final class EmailNotificationService extends NotificationService {
@Override
protected Channel createChannel() {
return new Email();
}
}
public static void main(String[] args) {
NotificationService smsService = new SmsNotificationService();
smsService.sendMessage();
NotificationService emailService = new EmailNotificationService();
emailService.sendMessage();
}
Output:
SMS Sent !!!
Email Sent !!!
NotificationService never says new Sms(). Adding a push channel means one new Channel class and one new subclass, and no edit to the base class. It fits frameworks that call your code and need a hook. In most business code, a simple factory or an injected object is easier than a subclass per product.
2.3 Abstract Factory
It creates a family of objects that must match each other. Our service runs on AWS or on Google Cloud, and each cloud needs a matching queue and storage client. Mixing an AWS queue with a Google store would be a bug. The code has two product interfaces (Queue and Storage), two implementations of each (AwsQueue, GoogleQueue, AwsStorage, GoogleStorage), and one factory per cloud:
interface CloudServiceFactory {
Queue createQueue();
Storage createStorage();
}
class AwsCloudServiceFactory implements CloudServiceFactory {
@Override
public Queue createQueue() {
return new AwsQueue();
}
@Override
public Storage createStorage() {
return new AwsStorage();
}
}
class GoogleCloudServiceFactory implements CloudServiceFactory {
@Override
public Queue createQueue() {
return new GoogleQueue();
}
@Override
public Storage createStorage() {
return new GoogleStorage();
}
}
The client picks a factory once, and then only asks it for products:
public static void main(String[] args) {
// Create AWS service family.
CloudServiceFactory awsFactory = new AwsCloudServiceFactory();
Queue awsQueue = awsFactory.createQueue();
Storage awsStorage = awsFactory.createStorage();
awsQueue.offer("Item");
awsQueue.poll();
awsStorage.save("File");
awsStorage.get();
// Create Google Cloud service family.
CloudServiceFactory googleFactory = new GoogleCloudServiceFactory();
Queue googleQueue = googleFactory.createQueue();
Storage googleStorage = googleFactory.createStorage();
googleQueue.offer("Item");
googleQueue.poll();
googleStorage.save("File");
googleStorage.get();
}
The first family prints Saved to SQS !!! and Saved to S3 !!!. The second prints Saved to CloudTasks !!! and Saved to GCS !!!. The rest of the program sees only Queue and Storage. Switching cloud is a one-line change where the factory is chosen. It is the heaviest factory, so use it only for real families.
3. Builder
An alert has two required fields (email and message) and two optional ones (title and description). A constructor with four string parameters is hard to read: new Alert("a@b.com", "Paid", "", null). Which one is the title? One constructor per combination (the "telescoping constructor" problem) is worse. Setters fix the readability but make the object mutable and allow half-built objects.
A builder collects the values, checks them, and creates an immutable object in one step:
final class Alert {
private final String email;
private final String message;
private final String title;
private final String description;
// Private constructor ensures object creation through the Builder.
private Alert(Builder builder) {
this.email = builder.email;
this.message = builder.message;
this.title = builder.title;
this.description = builder.description;
}
public static class Builder {
// Mandatory fields.
private final String email;
private final String message;
// Optional fields.
private String title;
private String description;
public Builder(String email, String message) {
this.email = email;
this.message = message;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Alert build() {
if (email == null || email.isBlank()) {
throw new IllegalArgumentException("Invalid Email");
}
if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Message cannot be empty");
}
return new Alert(this);
}
}
}
public static void main(String[] args) {
Alert alert = new Alert.Builder("anc@gmail.com", "Message")
.title("")
.build();
}
What this gives you:
- Readable calls. Every value has a name at the call site:
.title("Billing"). - Valid objects only. All checks run in
build(). Required fields go in the builder's constructor, so they cannot be forgotten. A blank email throwsInvalid Email, and an empty message throwsMessage cannot be empty. An invalidAlertcan never exist (fail fast, as in the LLD interview lesson). - Immutable result. All fields are
finaland the constructor is private, so the only way in is the builder.
When not to use it. For three or four fields, a plain constructor or a Java record is simpler. A record with a compact constructor can hold the checks. Libraries such as Lombok (@Builder) generate builders, but in an interview you should be able to write one by hand. A builder is not thread-safe, so create one per object and do not share it.
4. Singleton
A singleton is a class with exactly one instance and one way to reach it. Typical uses are a configuration holder, a logger, a metrics registry or a connection pool. It is the easiest pattern to write and the easiest to misuse.
4.1 Ways to Build One
| Way | Lazy | Thread-safe | Note |
|---|---|---|---|
| Eager (field or static block) | No | Yes | Simplest. Created when the class loads, even if never used. A static block can handle an exception |
| Holder class | Yes | Yes | Best general choice. No locks, no volatile |
| Enum | Yes | Yes | Safe against reflection and serialization |
| Double-checked locking | Yes | Only with volatile |
Classic interview question. Easy to get wrong |
The simplest version is the eager one. The JVM creates the instance once, when the class is initialized:
public class EagerSingleton {
// Creates a single instance during class initialization.
// static ensures one instance per class, and final prevents reassignment.
private static final EagerSingleton INSTANCE = new EagerSingleton();
// Private constructor prevents external instantiation.
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
The holder class is lazy. The JVM loads a nested class only when it is first used, and class loading is thread-safe, so no lock is needed:
public class HolderLazySingleton {
// Private constructor prevents external instantiation.
private HolderLazySingleton() {
}
private static class Holder {
// Singleton instance created once during Holder class initialization.
private static final HolderLazySingleton INSTANCE =
new HolderLazySingleton();
}
public static HolderLazySingleton getInstance() {
return Holder.INSTANCE;
}
}
The enum version is the shortest. Java guarantees one instance, even against reflection and serialization, which can both create a second instance of a normal class:
public enum EnumSingleton {
// The single Singleton instance.
INSTANCE;
public void doSomething() {
// Business logic goes here.
}
}
Double-checked locking is lazy and avoids taking a lock on every call:
public class DoubleCheckedLockingSingleton {
// volatile ensures visibility across threads and prevents unsafe
// instruction reordering during instance initialization.
private static volatile DoubleCheckedLockingSingleton INSTANCE;
// Private constructor prevents external instantiation.
private DoubleCheckedLockingSingleton() {
}
public static DoubleCheckedLockingSingleton getInstance() {
// First check: Avoid acquiring the lock if the instance already exists.
if (INSTANCE == null) {
// Acquire the class-level lock before instance creation.
synchronized (DoubleCheckedLockingSingleton.class) {
// Second check: Another thread might have initialized it
// while the current thread was waiting for the lock.
if (INSTANCE == null) {
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
The volatile keyword is the part people forget. Without it, the compiler or CPU may reorder the steps of new, so another thread can see a non-null reference to an object that is not fully built. The concurrency lesson explains this in detail.
4.2 Protecting Against Reflection and Serialization
A plain double-checked singleton can be broken in two ways. Reflection calls the private constructor with setAccessible(true) and gets a second object. Serialization writes the object to bytes, and reading it back creates a copy. The protected version closes both gaps:
public class ProtectedDoubleCheckedLockingSingleton implements Serializable {
private static final long serialVersionUID = 1L;
// volatile ensures visibility across threads and prevents
// unsafe instruction reordering during instance initialization.
private static volatile ProtectedDoubleCheckedLockingSingleton INSTANCE;
// Private constructor prevents external instantiation.
// Additional check rejects constructor calls through reflection
// after the Singleton instance has been initialized.
private ProtectedDoubleCheckedLockingSingleton() {
if (INSTANCE != null) {
throw new IllegalStateException("Singleton instance already exists");
}
}
public static ProtectedDoubleCheckedLockingSingleton getInstance() {
// First check: Avoid synchronization if the instance already exists.
if (INSTANCE == null) {
synchronized (ProtectedDoubleCheckedLockingSingleton.class) {
// Second check: Another thread might have initialized it.
if (INSTANCE == null) {
INSTANCE = new ProtectedDoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
readResolvemakes deserialization return the existing instance instead of the copy.- The constructor check throws if an instance already exists. We tested it: a reflection call after the first
getInstance()throwsIllegalStateException.
The constructor check has a hole. It only works after the first getInstance(). If reflection runs first, no instance exists yet, the check passes, and then getInstance() creates a second one. We tested that too. An enum has no such hole, which is why it is the safest choice when this matters.
4.3 Why Singleton Is Controversial
- Hidden dependencies. A class that calls
getInstance()inside its methods does not show the dependency in its constructor, so you cannot replace it. - Hard to test. Tests share the one instance, so state from one test leaks into the next. You cannot swap in a fake.
- Global mutable state. Any code can change it from anywhere. Bugs become hard to trace.
The fix is to separate "one instance" from "global access". Keep the single instance, but pass it in through constructors (dependency injection). Let a container create it once. Spring beans are singletons by default, yet the classes themselves are plain and testable. Keep any singleton read-only or stateless when you can.
A singleton is also one instance per JVM, not per system. With 10 servers behind a load balancer you have 10 "singletons". If the requirement is one for the whole cluster, such as one ID generator or one scheduler, a Java class cannot give you that. Use a shared store (a database row, Redis) or leader election (the consensus lesson). Say this in an interview. It shows that you know where the pattern stops.
5. Worked Example: One Alert, Three Patterns
A payment fails and the system must tell the customer. The demo files are separate programs, so here is how their real classes would fit together:
classDiagram
class Alert
class Builder {
+title(String) Builder
+description(String) Builder
+build() Alert
}
class NotificationService {
<<abstract>>
#createChannel() Channel
+sendMessage()
}
class Channel {
<<interface>>
+send()
}
class CloudServiceFactory {
<<interface>>
+createQueue() Queue
+createStorage() Storage
}
Builder ..> Alert : builds
NotificationService ..> Channel : creates
SmsNotificationService --|> NotificationService
EmailNotificationService --|> NotificationService
Sms ..|> Channel
Email ..|> Channel
AwsCloudServiceFactory ..|> CloudServiceFactory
GoogleCloudServiceFactory ..|> CloudServiceFactory
- Builder creates the
Alertand rejects a blank email or message before anything is sent. - Factory Method lets
SmsNotificationServiceorEmailNotificationServicechoose the channel, whilesendMessage()stays the same. - Abstract Factory gives the deployment a matching queue and store: SQS and S3 on AWS, Cloud Tasks and Cloud Storage on Google.
- Singleton fits the one object that should exist once per JVM, such as a read-only configuration holder, built with the holder class or an enum and passed in by the wiring code.
Adding a push channel touches nothing that exists: one new Channel class and one new subclass. Moving from AWS to Google changes the one line where the factory is chosen. That is what the open/closed rule from the SOLID lesson looks like in code.
6. Common Pitfalls
- A factory for one class. If there is only one implementation, a plain
newis fine. - Mixing families. The point of Abstract Factory is that products match. If a client creates
AwsQueueby hand next to a Google store, the pattern is lost. - A builder without validation. It adds code and checks nothing. Put the rules in
build(). - Double-checked locking without
volatile. It looks right and fails only now and then, in strange ways. Use the holder class or an enum. - Trusting the constructor check. It protects only after the first
getInstance(). For real safety use an enum. - Thinking singleton means one in the whole system. It means one per JVM.
7. Interview Questions This Lesson Prepares You For
- What is the difference between a simple factory, Factory Method and Abstract Factory? A simple factory is one method that returns an interface. Factory Method lets subclasses decide which class to create, inside a fixed workflow. Abstract Factory creates a family of matching objects, such as a queue and a store for one cloud.
- When do you choose a builder over a constructor? When there are many fields, several are optional, or the object must be immutable and valid. The builder names each value at the call site and checks all rules in
build(). For three or four fields, a constructor or record is simpler. - Write a thread-safe singleton. Use the holder class idiom or a single-element enum. If asked for double-checked locking, show the
volatilefield and both null checks, and explain thatvolatilestops another thread from seeing a half-built object. - How can a singleton be broken, and how do you prevent it? Reflection can call a private constructor, serialization can create a copy, and several class loaders can load the class twice.
readResolvefixes serialization. A constructor check helps with reflection only after the instance exists. An enum protects against the first two. - Why do many people call singleton an anti-pattern? It creates hidden global state, makes tests share data, and hides dependencies. The fix is to let a container create one instance and inject it, so the class stays a normal class.
- You run 10 servers. Can a singleton give you one ID generator for all of them? No. A singleton is one per JVM, so there are 10. For one per cluster use a database or Redis, or elect a leader.
- How would you add a new product type without changing existing code? With Factory Method, add one class and one subclass. With a simple factory, keep a registry that maps a type to a
Supplier, or let a DI container collect all implementations of the interface.