Skills101

AdvancedOOP Concepts · Lesson 10 of 10 · Updated ·

Singleton, Factory and Builder in Java — Creational Design Patterns With Code

Creational patterns answer one question: who creates an object, and how? Writing new everywhere works for small programs, but it causes problems when an object must exist only once, when the exact class depends on input, or when a constructor needs eight arguments. The earlier design-patterns lesson introduced the names. Here we write each pattern properly in Java, including the details interviewers check.

1. Singleton: exactly one object

A Singleton class allows only one instance in the whole program and gives a global way to reach it. Typical uses: application configuration, a connection pool, a logger.

The three rules:

  1. Make the constructor private, so nobody outside can call new.
  2. Keep the single instance in a static field.
  3. Provide a static method that returns it.

The cleanest thread-safe version for most code is the holder idiom. The JVM loads the inner Holder class only when getInstance() is first called, and class loading is thread-safe, so there is no synchronized and no race:

class AppConfig {
    private static int created = 0;
    private final String collegeName;

    private AppConfig() {                 // 1. nobody outside can call new
        created++;
        collegeName = "Skills101 College";
    }

    private static class Holder {          // 2. loaded only on first use
        static final AppConfig INSTANCE = new AppConfig();
    }

    static AppConfig getInstance() {       // 3. global access point
        return Holder.INSTANCE;
    }

    String collegeName() { return collegeName; }
    static int created() { return created; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Objects before first call: " + AppConfig.created());
        AppConfig a = AppConfig.getInstance();
        AppConfig b = AppConfig.getInstance();
        System.out.println("Same object? " + (a == b));
        System.out.println("Objects created: " + AppConfig.created());
        System.out.println(a.collegeName());
    }
}
Objects before first call: 0
Same object? true
Objects created: 1
Skills101 College

The first line proves the object is created lazily — only when first needed.

Five ways to write a Java Singleton compared: eager field, synchronized method, double-checked locking with volatile, holder class and enum, by laziness, thread safety and speed

Other versions you will be asked about

VersionHowNotes
Eagerstatic final AppConfig INSTANCE = new AppConfig();Simple, thread-safe, but created even if never used
Synchronized methodstatic synchronized AppConfig getInstance()Thread-safe, but every call takes a lock
Double-checked lockingcheck null, lock, check null againThe field must be volatile, otherwise another thread can see a half-built object
Holder idiomshown aboveLazy, thread-safe, no locking
Enumenum AppConfig { INSTANCE; }Also safe against reflection and serialization creating a second copy; recommended in Effective Java

A plain lazy version (if (instance == null) instance = new AppConfig();) without any locking is not thread-safe: two threads can both see null and create two objects.

Caution: a Singleton is global state. It makes unit testing harder because tests cannot easily replace it. In Spring applications you rarely write one by hand — Spring beans are singletons by default, and they are injected, which keeps them testable.

2. Factory: hide which class is created

A Factory is a method (or class) that decides which concrete class to create, so callers depend only on an interface. Example: a fee-payment screen supports UPI, card and net banking.

interface Payment {
    String pay(int amount);
}

class UpiPayment implements Payment {
    public String pay(int amount) { return "Paid Rs " + amount + " by UPI"; }
}

class CardPayment implements Payment {
    public String pay(int amount) {
        int fee = amount * 2 / 100;                  // 2% card charge
        return "Paid Rs " + (amount + fee) + " by card (incl. Rs " + fee + " fee)";
    }
}

class NetBankingPayment implements Payment {
    public String pay(int amount) { return "Paid Rs " + amount + " by net banking"; }
}

class PaymentFactory {
    static Payment create(String mode) {
        switch (mode.toUpperCase()) {
            case "UPI": return new UpiPayment();
            case "CARD": return new CardPayment();
            case "NETBANKING": return new NetBankingPayment();
            default: throw new IllegalArgumentException("Unknown mode: " + mode);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        for (String mode : new String[]{"upi", "card", "netbanking"}) {
            Payment p = PaymentFactory.create(mode);   // caller never writes new CardPayment()
            System.out.println(p.pay(4999));
        }
        try {
            PaymentFactory.create("cheque");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
Paid Rs 4999 by UPI
Paid Rs 5098 by card (incl. Rs 99 fee)
Paid Rs 4999 by net banking
Unknown mode: cheque

(The card fee is 4999 * 2 / 100 = 99 because integer division drops the decimal part.)

Why bother? The switch now lives in one place. Screens, reports and tests all call PaymentFactory.create(...); when "WALLET" is added, only the factory and the new class change. You have used factories already: List.of(...), Integer.valueOf(...) and Calendar.getInstance() are all factory methods.

3. Builder: many optional fields

A student-registration object may have two required fields (name, roll number) and many optional ones (email, phone, hostel, scholarship). Constructors get ugly fast:

new Student("Asha", 101, null, null, true, false)   // what is true? what is false?

This is the telescoping constructor problem: you need many overloaded constructors, and callers cannot tell which argument is which. The Builder pattern fixes it with named, chainable methods:

Telescoping constructors versus a builder: a call with six unnamed arguments compared with a chain of named builder methods ending in build()

class Student {
    private final String name;          // required
    private final int roll;             // required
    private final String email;         // optional
    private final boolean hostel;       // optional

    private Student(Builder b) {
        this.name = b.name;
        this.roll = b.roll;
        this.email = b.email;
        this.hostel = b.hostel;
    }

    public String toString() {
        return roll + " " + name + " | email=" + email + " | hostel=" + hostel;
    }

    static class Builder {
        private final String name;
        private final int roll;
        private String email = "not given";
        private boolean hostel = false;

        Builder(String name, int roll) {      // required fields go in the constructor
            this.name = name;
            this.roll = roll;
        }
        Builder email(String email) { this.email = email; return this; }   // return this → chaining
        Builder hostel(boolean hostel) { this.hostel = hostel; return this; }

        Student build() {
            if (roll <= 0) throw new IllegalStateException("roll must be positive");
            return new Student(this);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Student asha = new Student.Builder("Asha", 101).email("asha@college.in").hostel(true).build();
        Student ravi = new Student.Builder("Ravi", 102).build();
        System.out.println(asha);
        System.out.println(ravi);
        try {
            new Student.Builder("Neha", 0).build();
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
101 Asha | email=asha@college.in | hostel=true
102 Ravi | email=not given | hostel=false
Rejected: roll must be positive

Three benefits: every argument is named, optional fields get defaults, and build() is one place to validate the whole object before it exists. Because Student has only final fields and no setters, the result is also immutable. In real projects, StringBuilder, HttpRequest.newBuilder() and Lombok's @Builder follow this pattern.

4. Which one when?

ProblemPattern
Exactly one shared object (config, pool)Singleton (or a Spring singleton bean)
The class to create depends on input or configurationFactory
An object with many optional fields or validation across fieldsBuilder

Common mistakes

  • Lazy Singleton without synchronization — two threads can create two objects.
  • Double-checked locking without volatile on the instance field.
  • Using Singletons for everything; global state makes testing painful. Prefer dependency injection.
  • A factory that returns concrete types (CardPayment create(...)) — callers should receive the interface.
  • A builder whose build() does not validate, so invalid objects can still be created.

Quick recap

  • Singleton: private constructor + static instance + static accessor; holder idiom or enum for thread safety.
  • Factory: one method decides which class to create; callers depend on the interface.
  • Builder: named, chainable setters on a helper class, then build() validates and creates an immutable object.
  • All three are creational patterns: they control how objects are made.

Practice what you learned

📝 Quiz: Creational Patterns in Java5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →