Chapter 22 of 26

Creational Patterns: Singleton, Factory & Builder

In every program so far we created objects the direct way: new Student("Ravi"). That is perfectly fine for small programs. But in real applications, object creation itself often becomes a design problem:

  • Some objects should exist only once (one configuration, one connection pool).

  • Client code should not have to know which concrete class to create (email, SMS or WhatsApp notification?).

  • Some objects have so many optional fields that constructors become unreadable.

The creational patterns solve these problems by taking control of how and when objects are created. As we saw in Introduction to Design Patterns, the Gang of Four list five creational patterns. In this chapter we study the three you will meet most often in projects and interviews: Singleton, the Factory family (Simple Factory, Factory Method, Abstract Factory) and Builder.


Singleton Pattern

Singleton ensures that a class has only one instance, and provides a global point of access to that instance.

Think of the Election Commission of India. There is exactly one, and everybody who needs it reaches the same one. In software, typical candidates are an application configuration object, a logger, a cache, or a pool of database connections. Creating several of them would waste resources or, worse, give different parts of the program different settings.

Every Singleton implementation has three ingredients:

  1. A private constructor, so no other class can write new.

  2. A private static field that holds the one instance.

  3. A public static method (usually getInstance()) that returns it.

The interesting part is when the instance is created and whether that is thread-safe. Let's go through the approaches from simplest to best.

1. Eager Initialization

Create the instance in a static final field.

class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();   // created when the class is initialised

    private final String appName;
    private int maxUsers;

    private AppConfig() {                       // nobody outside can call new AppConfig()
        System.out.println("Loading configuration...");
        appName = "CS Learning Portal";
        maxUsers = 100;
    }

    public static AppConfig getInstance() {
        return INSTANCE;
    }

    public String getAppName() { return appName; }
    public int getMaxUsers() { return maxUsers; }
    public void setMaxUsers(int maxUsers) { this.maxUsers = maxUsers; }
}

class Main {
    public static void main(String[] args) {
        System.out.println("Program started");

        AppConfig c1 = AppConfig.getInstance();
        AppConfig c2 = AppConfig.getInstance();

        c1.setMaxUsers(500);
        System.out.println(c2.getAppName() + " allows " + c2.getMaxUsers() + " users");
        System.out.println("Same object? " + (c1 == c2));
    }
}

Output:

Program started
Loading configuration...
CS Learning Portal allows 500 users
Same object? true

Both c1 and c2 point to the same object, so a change through c1 is visible through c2.

Why is this thread-safe? The JVM initialises a class (runs its static initialisers) exactly once, and the Java Language Specification guarantees that class initialisation is properly synchronised. So even if many threads call getInstance() at the same time, only one object is ever created.

Notice the output order: "Program started" is printed before "Loading configuration...". The word "eager" is a little misleading in Java — the object is created when the class is initialised, which happens on the first real use of AppConfig, not when the program starts. The only real drawback is that any other access to the class (for example another static method) also triggers creation, even if getInstance() is never called.

2. Lazy Initialization (Not Thread-Safe)

A common first attempt is to create the object only when it is first requested:

public static LazySingleton getInstance() {
    if (instance == null) {          // check
        instance = new LazySingleton(); // then act
    }
    return instance;
}

This works in a single-threaded program. With threads it is a classic check-then-act race condition: two threads can both see instance == null before either has assigned it, and both create an object. Let's prove it. Below, eight threads call getInstance() at the same moment, and the constructor is made slow with sleep() to widen the race window:

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
        try {
            Thread.sleep(50);            // pretend the setup is slow
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static LazySingleton getInstance() {
        if (instance == null) {          // two threads can both see null here
            instance = new LazySingleton();
        }
        return instance;
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {
        Set<LazySingleton> seen = ConcurrentHashMap.newKeySet();
        CountDownLatch startSignal = new CountDownLatch(1);
        Thread[] threads = new Thread[8];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                try {
                    startSignal.await();
                } catch (InterruptedException e) {
                    return;
                }
                seen.add(LazySingleton.getInstance());
            });
            threads[i].start();
        }

        startSignal.countDown();         // release all threads together
        for (Thread t : threads) {
            t.join();
        }
        System.out.println("Distinct objects created: " + seen.size());
    }
}

Output (one run — the number changes from run to run):

Distinct objects created: 7

Our "singleton" produced seven objects! Without the sleep() the race happens less often, which is worse: the bug hides during testing and appears in production. (Threads, synchronized and race conditions are explained in the Java tutorial's multithreading chapters.)

3. Synchronized Method

The simplest fix is to make getInstance() synchronized, so only one thread at a time can run it:

class SyncSingleton {
    private static SyncSingleton instance;

    private SyncSingleton() { }

    public static synchronized SyncSingleton getInstance() {
        if (instance == null) {
            instance = new SyncSingleton();
        }
        return instance;
    }
}

This is correct, but every call pays for acquiring a lock, even though the lock is only needed for the very first call. For an object fetched millions of times, that is wasteful.

4. Double-Checked Locking (with volatile)

Check once without the lock (fast path), and only if the instance is still missing, lock and check again:

class DbConnectionPool {
    private static volatile DbConnectionPool instance;   // volatile is essential

    private DbConnectionPool() {
        System.out.println("Creating pool");
    }

    public static DbConnectionPool getInstance() {
        DbConnectionPool local = instance;               // one volatile read on the fast path
        if (local == null) {                             // 1st check, no lock
            synchronized (DbConnectionPool.class) {
                local = instance;
                if (local == null) {                     // 2nd check, with lock
                    local = new DbConnectionPool();
                    instance = local;
                }
            }
        }
        return local;
    }
}

Why two checks? Two threads may both pass the first check. The first one to get the lock creates the object; when the second one gets the lock, the second check stops it from creating another.

Why volatile? The statement instance = new DbConnectionPool() is not one step. Roughly, it means: allocate memory, run the constructor, store the reference. Without volatile, the compiler or CPU may reorder these so the reference becomes visible before the constructor has finished. Another thread doing the unlocked first check could then see a non-null but half-constructed object. Declaring the field volatile (correct since Java 5's memory model) forbids this reordering and guarantees that a thread which sees the reference also sees the fully constructed object.

The local variable local is a small optimisation: on the fast path it reads the volatile field only once.

Double-checked locking without volatile is broken in Java. This is one of the most frequently asked Singleton interview points.

5. Initialization-on-Demand Holder (Bill Pugh Singleton)

We can get laziness and thread safety without writing any locking code at all:

class Logger {
    private Logger() {
        System.out.println("Logger created");
    }

    private static class Holder {                        // loaded only when first used
        static final Logger INSTANCE = new Logger();
    }

    public static Logger getInstance() {
        return Holder.INSTANCE;
    }

    public void log(String msg) {
        System.out.println("[LOG] " + msg);
    }
}

The nested class Holder is not initialised when Logger is loaded — only when getInstance() first touches Holder.INSTANCE. The JVM's class-initialisation guarantee then makes the creation thread-safe, exactly as in the eager version. You get lazy creation, no synchronized on every call, and very little code.

6. Enum Singleton

enum IdGenerator {
    INSTANCE;

    private int next = 1;

    public synchronized int nextId() {
        return next++;
    }
}

An enum with a single constant is a singleton by definition: the JVM creates enum constants once, thread-safely. Effective Java (Joshua Bloch) recommends this as often the best way to implement a singleton, because it also handles the two attacks we will see next — reflection and serialization — for free. Its limitations: an enum cannot extend another class (it can implement interfaces), and it is not lazy in the "holder" sense.

Note that the enum only guarantees one instance. The instance's own mutable state still needs protecting, which is why nextId() is synchronized.

Here is a main that uses the four classes above (all in one file):

class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(SyncSingleton.getInstance() == SyncSingleton.getInstance());

        Runnable task = () -> DbConnectionPool.getInstance();
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println(DbConnectionPool.getInstance() == DbConnectionPool.getInstance());

        System.out.println("Before first use of Logger");
        Logger.getInstance().log("Holder idiom works");
        Logger.getInstance().log("Still the same logger");

        System.out.println(IdGenerator.INSTANCE.nextId());
        System.out.println(IdGenerator.INSTANCE.nextId());
    }
}

Output:

true
Creating pool
true
Before first use of Logger
Logger created
[LOG] Holder idiom works
[LOG] Still the same logger
1
2

"Creating pool" appears once even though two threads raced to create it, and "Logger created" appears only after "Before first use of Logger", which proves the holder version is lazy.

Breaking a Singleton: Reflection and Serialization

A private constructor stops ordinary code, but not reflection. And deserialization creates objects without calling the constructor at all.

import java.lang.reflect.Constructor;

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

enum PrinterEnum {
    INSTANCE
}

class Main {
    public static void main(String[] args) throws Exception {
        Constructor<Printer> c = Printer.class.getDeclaredConstructor();
        c.setAccessible(true);                          // bypass 'private'
        Printer hacked = c.newInstance();
        System.out.println("Class singleton broken? " + (hacked != Printer.getInstance()));

        try {
            Constructor<PrinterEnum> ce =
                PrinterEnum.class.getDeclaredConstructor(String.class, int.class);
            ce.setAccessible(true);
            ce.newInstance("COPY", 1);
        } catch (IllegalArgumentException e) {
            System.out.println("Enum singleton: " + e.getMessage());
        }
    }
}

Output:

Class singleton broken? true
Enum singleton: Cannot reflectively create enum objects

For a class-based singleton that implements Serializable, every deserialization also produces a brand-new object (writing the singleton to a byte stream and reading it back gives an object for which == with the original is false). The fix is a readResolve() method, which the serialization machinery calls to replace the freshly read copy with the real instance:

class Settings implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Settings INSTANCE = new Settings();
    private Settings() { }
    public static Settings getInstance() { return INSTANCE; }

    // Without this method, deserialization creates a brand-new object
    private Object readResolve() {
        return INSTANCE;
    }
}

With this method in place, the same round trip returns the original object (== gives true).

Cloning is a third, smaller risk: a singleton should simply not implement Cloneable (and if a parent class does, override clone() to throw CloneNotSupportedException). Enum singletons need none of these fixes.

Comparing the Approaches

Approach

Lazy?

Thread-safe?

Cost per call

Safe from reflection / serialization?

Eager static final

On class init

Yes

None

No / needs readResolve

Lazy, unsynchronised

Yes

No

None

No

synchronized method

Yes

Yes

Lock on every call

No

Double-checked locking + volatile

Yes

Yes (only with volatile)

One volatile read

No

Holder idiom

Yes

Yes

None

No / needs readResolve

Enum

On class init

Yes

None

Yes

Singleton in C++ and Python

In modern C++ the standard approach is the Meyers Singleton: a static local variable inside the access function. Since C++11 the language guarantees that a function-local static is initialised exactly once, even if several threads call the function at the same time.

#include <iostream>
#include <thread>
#include <vector>

class Config {
public:
    static Config& instance() {
        static Config obj;          // initialised once, thread-safe since C++11
        return obj;
    }

    Config(const Config&) = delete;             // no copies
    Config& operator=(const Config&) = delete;  // no assignment

    int maxUsers = 100;

private:
    Config() { std::cout << "Config constructed\n"; }
    ~Config() { std::cout << "Config destroyed\n"; }
};

int main() {
    std::vector<std::jthread> workers;
    for (int i = 0; i < 4; ++i) {
        workers.emplace_back([] { Config::instance(); });
    }
    workers.clear();                            // jthread joins on destruction

    Config::instance().maxUsers = 500;
    std::cout << "maxUsers = " << Config::instance().maxUsers << '\n';
    std::cout << "same? " << std::boolalpha
              << (&Config::instance() == &Config::instance()) << '\n';
}

Output:

Config constructed
maxUsers = 500
same? true
Config destroyed

Four threads called instance(), yet the constructor ran once. Deleting the copy constructor and copy assignment stops anyone from duplicating the object, and the destructor runs automatically at program exit (something Java has no equivalent for — see Constructors & Destructors).

In Python, a module is executed only once and then cached, so the usual idiom is simply a module-level object (for example config = Config() in config.py) that every other module imports.

When (Not) to Use Singleton

Singleton is the most famous pattern and also the most criticised:

  • It is really global state in disguise; any class can reach it and change it, which creates hidden dependencies.

  • It makes unit testing hard, because you cannot easily replace the real object with a fake one.

  • A class that controls its own instance count and does its real job has two responsibilities.

Modern frameworks (Spring, for example) usually create one shared object and inject it where needed (dependency injection, from SOLID: Interface Segregation & Dependency Inversion). You get "only one instance" without the static access point. Use the classic Singleton for truly unique, stateless-ish resources, and prefer injection in larger applications.


Factory Patterns

Look at this code spread across an application:

Notification n;
if (channel.equals("email")) {
    n = new EmailNotification();
} else if (channel.equals("sms")) {
    n = new SmsNotification();
} else {
    n = new WhatsAppNotification();
}

Every place that needs a notification repeats this if-else, and every one of them depends on all three concrete classes. Adding "Push notification" means hunting down and editing every copy. The factory patterns fix this by moving the new calls into one place.

Simple Factory

A Simple Factory is a class with a method that decides which concrete class to instantiate based on its input, and returns it through a common interface.

interface Notification {
    void send(String to, String message);
}

class EmailNotification implements Notification {
    @Override
    public void send(String to, String message) {
        System.out.println("Email to " + to + ": " + message);
    }
}

class SmsNotification implements Notification {
    @Override
    public void send(String to, String message) {
        System.out.println("SMS to " + to + ": " + message);
    }
}

class WhatsAppNotification implements Notification {
    @Override
    public void send(String to, String message) {
        System.out.println("WhatsApp to " + to + ": " + message);
    }
}

// Simple Factory: one place that knows the concrete classes
class NotificationFactory {
    public static Notification create(String channel) {
        return switch (channel.toLowerCase()) {
            case "email"    -> new EmailNotification();
            case "sms"      -> new SmsNotification();
            case "whatsapp" -> new WhatsAppNotification();
            default -> throw new IllegalArgumentException("Unknown channel: " + channel);
        };
    }
}

class Main {
    public static void main(String[] args) {
        String[] userChoices = {"email", "SMS", "whatsapp"};
        for (String choice : userChoices) {
            Notification n = NotificationFactory.create(choice);   // client never says 'new EmailNotification()'
            n.send("priya", "Your exam starts at 10 AM");
        }
        try {
            NotificationFactory.create("pigeon");
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Email to priya: Your exam starts at 10 AM
SMS to priya: Your exam starts at 10 AM
WhatsApp to priya: Your exam starts at 10 AM
Error: Unknown channel: pigeon

The client depends only on the Notification interface. The knowledge of concrete classes lives in exactly one method. (The arrow-style switch expression is standard since Java 14.)

Strictly speaking, Simple Factory is not one of the 23 GoF patterns — it is a widely used programming idiom. Its weakness is that adding a new type still means editing the factory's switch, which bends the Open/Closed Principle. The GoF patterns below avoid that.

Factory Method (GoF)

Factory Method defines an interface for creating an object, but lets subclasses decide which class to instantiate.

The idea: a base class contains a workflow that needs some object, but instead of creating it with new, it calls an abstract "factory method". Each subclass overrides that method to return a different product.

interface Report {
    String render(String title, int value);
}

class PdfReport implements Report {
    public String render(String title, int value) {
        return "[PDF] " + title + " = " + value;
    }
}

class ExcelReport implements Report {
    public String render(String title, int value) {
        return "[XLSX] | " + title + " | " + value + " |";
    }
}

// Creator: contains the common workflow and a factory method
abstract class ReportGenerator {

    protected abstract Report createReport();          // the factory method

    public void generate(String title, int value) {
        Report report = createReport();                 // subclass decides which class
        System.out.println(report.render(title, value));
    }
}

class PdfReportGenerator extends ReportGenerator {
    @Override
    protected Report createReport() {
        return new PdfReport();
    }
}

class ExcelReportGenerator extends ReportGenerator {
    @Override
    protected Report createReport() {
        return new ExcelReport();
    }
}

class Main {
    public static void main(String[] args) {
        ReportGenerator g1 = new PdfReportGenerator();
        ReportGenerator g2 = new ExcelReportGenerator();
        g1.generate("Students placed", 312);
        g2.generate("Students placed", 312);
    }
}

Output:

[PDF] Students placed = 312
[XLSX] | Students placed | 312 |

The roles are:

        Creator (abstract)                         Product (interface)
        ReportGenerator  ──── uses ────────────▶   Report
        + generate()                                  ▲
        # createReport()                     ┌────────┴────────┐
               ▲                         PdfReport        ExcelReport
       ┌───────┴──────────────┐              ▲                 ▲
PdfReportGenerator    ExcelReportGenerator   │ new             │ new
  createReport() ────────────────────────────┘                 │
                        createReport() ────────────────────────┘

generate() is written once and never changes. To support a new format, you add a new Report class and a new generator subclass — no existing code is edited. Notice the similarity to Template Method from the previous chapter: Factory Method is often a step inside a template method.

Abstract Factory (GoF)

Abstract Factory provides an interface for creating families of related objects without specifying their concrete classes.

Use it when products must match each other. A dark-theme screen must use a dark button and a dark checkbox; mixing a dark button with a light checkbox would be a bug. One factory object creates the whole family:

interface Button   { String draw(); }
interface Checkbox { String draw(); }

class LightButton   implements Button   { public String draw() { return "white button"; } }
class LightCheckbox implements Checkbox { public String draw() { return "white checkbox"; } }
class DarkButton    implements Button   { public String draw() { return "black button"; } }
class DarkCheckbox  implements Checkbox { public String draw() { return "black checkbox"; } }

// Abstract Factory: one factory creates a whole family of matching products
interface ThemeFactory {
    Button createButton();
    Checkbox createCheckbox();
}

class LightThemeFactory implements ThemeFactory {
    public Button createButton()     { return new LightButton(); }
    public Checkbox createCheckbox() { return new LightCheckbox(); }
}

class DarkThemeFactory implements ThemeFactory {
    public Button createButton()     { return new DarkButton(); }
    public Checkbox createCheckbox() { return new DarkCheckbox(); }
}

class LoginScreen {
    private final Button button;
    private final Checkbox remember;

    LoginScreen(ThemeFactory factory) {
        button = factory.createButton();
        remember = factory.createCheckbox();
    }

    void show() {
        System.out.println(button.draw() + " + " + remember.draw());
    }
}

class Main {
    public static void main(String[] args) {
        boolean darkMode = true;
        ThemeFactory factory = darkMode ? new DarkThemeFactory() : new LightThemeFactory();
        new LoginScreen(factory).show();
        new LoginScreen(new LightThemeFactory()).show();
    }
}

Output:

black button + black checkbox
white button + white checkbox

LoginScreen never mentions a concrete class. Switching the whole UI theme means passing a different factory. The cost: adding a new kind of product (say, a Slider) requires changing the ThemeFactory interface and every factory that implements it.

Static Factory Methods

You will also see the word "factory" used for static methods that return objects, such as List.of(1, 2, 3), Integer.valueOf(42) or LocalDate.of(2026, 11, 2). Compared with constructors, they can have meaningful names, can return a cached object instead of a new one (Integer.valueOf caches −128 to 127), and can return any subtype. They follow the factory idea but are not the GoF Factory Method pattern, which relies on subclasses overriding a method.

Simple Factory vs Factory Method vs Abstract Factory

Feature

Simple Factory

Factory Method

Abstract Factory

GoF pattern?

No (idiom)

Yes

Yes

How the class is chosen

Parameter + switch/if

Subclass overrides a method (inheritance)

Client is given a factory object (composition)

Creates

One product

One product

A family of related products

Adding a new product type

Edit the factory

Add a new subclass

Add a new factory class (easy); add a new product kind (hard)


Builder Pattern

The Problem: Telescoping Constructors

Suppose a UserProfile has two required fields (name, email) and four optional ones. With constructors only, you end up with a "telescope" of overloads:

UserProfile(String name, String email)
UserProfile(String name, String email, String phone)
UserProfile(String name, String email, String phone, String city)
UserProfile(String name, String email, String phone, String city, int year)
UserProfile(String name, String email, String phone, String city, int year, boolean newsletter)

And then a call like this:

new UserProfile("Rahul", "rahul@example.com", null, null, 0, true);

What is 0? What is true? If you accidentally swap phone and city (both String), the compiler cannot help you. The alternative — an empty constructor plus setters — makes the object mutable and allows it to exist in a half-filled, invalid state.

Builder separates the construction of a complex object from its representation, so that the same step-by-step construction process can create different representations.

In Java, the common form (popularised by Effective Java) is a static nested Builder class with one method per optional field, each returning this so calls can be chained, and a final build() that validates and creates the object.

class UserProfile {
    // all fields final: the object is immutable once built
    private final String name;      // required
    private final String email;     // required
    private final String phone;     // optional
    private final String city;      // optional
    private final int graduationYear; // optional
    private final boolean newsletter; // optional

    private UserProfile(Builder b) {
        this.name = b.name;
        this.email = b.email;
        this.phone = b.phone;
        this.city = b.city;
        this.graduationYear = b.graduationYear;
        this.newsletter = b.newsletter;
    }

    @Override
    public String toString() {
        return "UserProfile{name=" + name + ", email=" + email + ", phone=" + phone
                + ", city=" + city + ", year=" + graduationYear + ", newsletter=" + newsletter + "}";
    }

    public static class Builder {
        private final String name;
        private final String email;
        private String phone = "not given";
        private String city = "not given";
        private int graduationYear = 0;
        private boolean newsletter = false;

        public Builder(String name, String email) {    // required values go in the constructor
            this.name = name;
            this.email = email;
        }

        public Builder phone(String phone) { this.phone = phone; return this; }
        public Builder city(String city) { this.city = city; return this; }
        public Builder graduationYear(int year) { this.graduationYear = year; return this; }
        public Builder newsletter(boolean value) { this.newsletter = value; return this; }

        public UserProfile build() {
            if (name == null || name.isBlank()) {
                throw new IllegalStateException("name is required");
            }
            if (email == null || !email.contains("@")) {
                throw new IllegalStateException("invalid email: " + email);
            }
            return new UserProfile(this);
        }
    }
}

class Main {
    public static void main(String[] args) {
        UserProfile u1 = new UserProfile.Builder("Ananya", "ananya@example.com")
                .city("Pune")
                .graduationYear(2027)
                .build();

        UserProfile u2 = new UserProfile.Builder("Rahul", "rahul@example.com")
                .phone("98xxxxxx10")
                .newsletter(true)
                .build();

        System.out.println(u1);
        System.out.println(u2);

        try {
            new UserProfile.Builder("Ghost", "no-at-sign").build();
        } catch (IllegalStateException e) {
            System.out.println("Build failed: " + e.getMessage());
        }
    }
}

Output:

UserProfile{name=Ananya, email=ananya@example.com, phone=not given, city=Pune, year=2027, newsletter=false}
UserProfile{name=Rahul, email=rahul@example.com, phone=98xxxxxx10, city=not given, year=0, newsletter=true}
Build failed: invalid email: no-at-sign

What we gained:

  • Readable calls: .city("Pune") says exactly what the value means.

  • Any combination of optional fields, in any order, without dozens of constructors.

  • Immutable result: all fields of UserProfile are final and there are no setters.

  • Validation in one place: build() checks everything before an object ever exists, so an invalid UserProfile can never be created. The constructor is private, so the builder is the only way in.

The cost is extra code (the builder repeats every field). In real projects, the Lombok library's @Builder annotation generates it automatically. The JDK uses builders too: StringBuilder builds a String piece by piece, and HttpRequest.newBuilder().uri(...).header(...).build() (Java 11+) builds an HTTP request.

The original GoF Builder is a little more general: a Director drives an abstract Builder through the same construction steps, and different concrete builders produce different representations (for example, the same document built as HTML or as PDF). The fluent nested builder above is the form you will write most often.

Builder vs Factory

Factory

Builder

Answers "which class should I create?"

Answers "how do I assemble this complex object?"

Usually creates the object in one call

Creates the object step by step, then build()

Returns an interface/abstract type

Usually returns one concrete class

Hides concrete classes from the client

Hides a messy constructor and validation from the client


Common Mistakes

  • Lazy Singleton without synchronisation in multithreaded code — it can create several instances, as our demo showed.

  • Double-checked locking without volatile — another thread may see a half-constructed object.

  • Forgetting the private constructor, so anyone can still write new.

  • Using Singleton as a global variable bag for unrelated data, making the code hard to test.

  • Calling Simple Factory "the Factory Method pattern". Factory Method relies on subclasses overriding a creation method.

  • A Builder that returns a mutable object or skips validation, losing the main benefits.

  • Using Builder for a class with two fields. A constructor is clearer; builders pay off around four or more parameters, especially optional ones.


Interview Questions

How do you make a Singleton thread-safe in Java? Which approach is best?

Options: eager static final initialisation, a synchronized getInstance(), double-checked locking with a volatile field, the holder (Bill Pugh) idiom, or an enum. The enum approach is usually considered best because it is thread-safe and also resists reflection and serialization; the holder idiom is the best lazy class-based option.

Why is volatile needed in double-checked locking?

Object creation is not atomic: memory allocation, constructor execution and reference assignment may be reordered. Without volatile, another thread could see a non-null reference to an object whose constructor has not finished. volatile forbids that reordering and ensures safe publication.

How can a Singleton be broken and how do you prevent it?

By reflection (calling the private constructor via setAccessible(true)), by deserialization (creates a new object) and by cloning. Prevent with an enum singleton, or for a class: throw from the constructor if an instance already exists, add readResolve(), and don't support cloning.

What is the difference between Factory Method and Abstract Factory?

Factory Method uses inheritance: a subclass overrides one method to decide which single product to create. Abstract Factory uses composition: the client receives a factory object whose several methods create a whole family of related products that are meant to be used together.

When would you use the Builder pattern?

When an object has many parameters, especially optional ones, or needs validation before it exists, and you want it immutable. It avoids telescoping constructors and unreadable calls with many null/false arguments.

Give JDK examples of creational patterns.

Singleton: Runtime.getRuntime(). Static factory methods: List.of(), Integer.valueOf(), Calendar.getInstance(). Builder: StringBuilder, HttpRequest.newBuilder(). Prototype: clone().


Summary

  • Singleton: private constructor + static instance + static accessor. Thread-safe options are eager init, synchronized, double-checked locking with volatile, the holder idiom and the enum (the most robust).

  • Class-based singletons can be broken by reflection and serialization; enums cannot. In C++, use a function-local static (Meyers Singleton).

  • Singletons are global state; in big systems prefer one instance managed by dependency injection.

  • Simple Factory centralises new calls (idiom); Factory Method lets subclasses choose the product; Abstract Factory creates matching families of products.

  • Builder constructs complex, often immutable objects step by step with readable, validated calls.

Creational patterns decide how objects are born. In the next chapter, Structural Patterns: Adapter, Decorator & Facade, we will see how existing objects can be wrapped and combined into larger structures.