SyntaxPilot
Courses/Java/Lesson 46
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 46 of 51

Design patterns: Singleton, Factory, Builder, Observer, Strategy

queued

These are the notes for Java episode 46. Ravi's chai stall app has grown, and it keeps meeting problems that every big program meets: duplicate token numbers, object creation copied everywhere, constructors with six arguments, a kitchen that must know every listener, and an offer if-else chain that grows every week. For each one we watch the obvious code fail, then invent the fix. The fixes have names: design patterns. Every program was run with javac 21; outputs are copied from the runs.

What is a design pattern?

A design pattern is a named, proven solution to a design problem that keeps coming back. It is not a library you download; it is an idea you write in your own code. Patterns were made famous by the 1994 book Design Patterns: Elements of Reusable Object-Oriented Software by four authors known as the Gang of Four (GoF), which describes 23 patterns in three groups:

Group About Examples
Creational creating objects Singleton, Factory Method, Builder, Abstract Factory, Prototype
Structural how objects fit together Adapter, Decorator, Facade, Proxy, Composite
Behavioral how objects talk Observer, Strategy, Command, Iterator, Template Method

1. Singleton: exactly one shared object

Real-life example: one token machine. If the cash counter and the phone orders each have their own token machine, two customers get token 1.

class TokenCounter {
    private int next = 1;
    int nextToken() { return next++; }
}

public class Main {
    public static void main(String[] args) {
        TokenCounter counter1 = new TokenCounter();   // the cash counter
        TokenCounter counter2 = new TokenCounter();   // the phone orders

        System.out.println("Cash order:  token " + counter1.nextToken());
        System.out.println("Phone order: token " + counter2.nextToken());
        System.out.println("Cash order:  token " + counter1.nextToken());
    }
}

Output:

Cash order:  token 1
Phone order: token 1
Cash order:  token 2

Each new creates a separate counter with its own count. The fix: the class makes its own single instance and makes the constructor private.

class TokenCounter {
    private static final TokenCounter INSTANCE = new TokenCounter();
    private int next = 1;

    private TokenCounter() {}                     // nobody else can say new

    static TokenCounter getInstance() { return INSTANCE; }
    int nextToken() { return next++; }
}

public class Main {
    public static void main(String[] args) {
        TokenCounter cash = TokenCounter.getInstance();
        TokenCounter phone = TokenCounter.getInstance();

        System.out.println("Cash order:  token " + cash.nextToken());
        System.out.println("Phone order: token " + phone.nextToken());
        System.out.println("Cash order:  token " + cash.nextToken());
        System.out.println("Same object? " + (cash == phone));
    }
}

Output:

Cash order:  token 1
Phone order: token 2
Cash order:  token 3
Same object? true

Trying to make another one:

class TokenCounter {
    private static final TokenCounter INSTANCE = new TokenCounter();
    private int next = 1;

    private TokenCounter() {}                     // nobody else can say new

    static TokenCounter getInstance() { return INSTANCE; }
    int nextToken() { return next++; }
}

public class Main {
    public static void main(String[] args) {
        TokenCounter cash = TokenCounter.getInstance();
        TokenCounter phone = TokenCounter.getInstance();

        System.out.println("Cash order:  token " + cash.nextToken());
        System.out.println("Phone order: token " + phone.nextToken());
        System.out.println("Cash order:  token " + cash.nextToken());
        System.out.println("Same object? " + (cash == phone));
        TokenCounter extra = new TokenCounter();
    }
}

Compiler output:

Main.java:20: error: TokenCounter() has private access in TokenCounter
        TokenCounter extra = new TokenCounter();
                             ^
1 error
  • private static final INSTANCE is created when the class is loaded (episode 43). The JVM loads a class once, so this is thread-safe.
  • An even simpler singleton is an enum with one value (see Practice 1).
  • Use carefully: a singleton is global state. Tests share it (episode 44), and code that grabs it from anywhere is hard to change. Often it's better to create one object in main and pass it to whoever needs it (this is called dependency injection).

2. Factory: one place that creates objects

Real-life example: the order window. You say "one cutting chai" at the window; the kitchen is the one place that knows how to make it; and if they don't make something, they say so clearly.

interface Payment { String pay(int amount); }
class Upi  implements Payment { public String pay(int a) { return "Rs " + a + " by UPI"; } }
class Card implements Payment { public String pay(int a) { return "Rs " + a + " by card"; } }
class Cash implements Payment { public String pay(int a) { return "Rs " + a + " in cash"; } }

public class Main {
    // this if-chain is copied into the counter, the app and the delivery screen...
    static Payment choose(String type) {
        Payment p = null;
        if (type.equals("upi")) p = new Upi();
        else if (type.equals("card")) p = new Card();
        else if (type.equals("cash")) p = new Cash();
        return p;
    }

    public static void main(String[] args) {
        System.out.println(choose("upi").pay(45));
        System.out.println(choose("card").pay(162));
        System.out.println(choose("UPI").pay(30));      // the app sends capitals
    }
}

Output:

Rs 45 by UPI
Rs 162 by card
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Payment.pay(int)" because the return value of "Main.choose(String)" is null
    at Main.main(Main.java:19)

"UPI" in capitals matched nothing, choose returned null, and the program crashed later, far from the real mistake. And every copy of the chain must be edited to add a new payment type.

interface Payment { String pay(int amount); }
class Upi  implements Payment { public String pay(int a) { return "Rs " + a + " by UPI"; } }
class Card implements Payment { public String pay(int a) { return "Rs " + a + " by card"; } }
class Cash implements Payment { public String pay(int a) { return "Rs " + a + " in cash"; } }

class PaymentFactory {
    static Payment create(String type) {
        return switch (type.toLowerCase()) {
            case "upi"  -> new Upi();
            case "card" -> new Card();
            case "cash" -> new Cash();
            default -> throw new IllegalArgumentException("Unknown payment type: " + type);
        };
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(PaymentFactory.create("upi").pay(45));
        System.out.println(PaymentFactory.create("UPI").pay(30));
        System.out.println(PaymentFactory.create("cheque").pay(10));
    }
}

Output:

Rs 45 by UPI
Rs 30 by UPI
Exception in thread "main" java.lang.IllegalArgumentException: Unknown payment type: cheque
    at PaymentFactory.create(Main.java:12)
    at Main.main(Main.java:21)
  • Callers say PaymentFactory.create(type) and only know the Payment interface.
  • Case handling is fixed in one place; an unknown type fails loudly with a clear message instead of returning null.
  • Adding a wallet = one new class + one new case (Practice 2).
  • Factories in the JDK: List.of(...), Executors.newFixedThreadPool(...) (episode 41), LocalDate.of(...) (episode 42).

3. Builder: objects with many optional fields

Real-life example: an order slip with six unlabelled blanks. "true, false, 1, null": which blank was takeaway and which was extra hot?

class Order {
    String tea; int cups; boolean takeaway; boolean extraHot; int sugar; String note;

    Order(String tea, int cups, boolean takeaway, boolean extraHot, int sugar, String note) {
        this.tea = tea; this.cups = cups; this.takeaway = takeaway;
        this.extraHot = extraHot; this.sugar = sugar; this.note = note;
    }
    public String toString() {
        return cups + " x " + tea + (takeaway ? ", takeaway" : ", dine-in")
             + (extraHot ? ", extra hot" : "") + ", sugar " + sugar + (note == null ? "" : ", " + note);
    }
}

public class Main {
    public static void main(String[] args) {
        // Wanted: 2 masala chai, extra hot, to drink here, 1 spoon sugar
        Order o = new Order("masala chai", 2, true, false, 1, null);
        System.out.println(o);
    }
}

Output:

2 x masala chai, takeaway, sugar 1

We wanted extra hot, to drink here, and got takeaway, not extra hot: the two boolean arguments were swapped, and the compiler can't notice. A constructor with a long list of same-typed arguments is called a telescoping constructor.

class Order {
    private final String tea; private final int cups;
    private final boolean extraHot, takeaway;
    private Order(Builder b) {
        tea = b.tea; cups = b.cups; extraHot = b.extraHot; takeaway = b.takeaway;
    }
    public String toString() {
        return cups + " x " + tea + (extraHot ? ", extra hot" : "") + (takeaway ? ", takeaway" : ", dine-in");
    }
    static class Builder {
        private String tea; private int cups = 1; private boolean extraHot, takeaway;
        Builder tea(String t) { tea = t; return this; }
        Builder cups(int n)   { cups = n; return this; }
        Builder extraHot()    { extraHot = true; return this; }
        Builder takeaway()    { takeaway = true; return this; }
        Order build() {
            if (tea == null) throw new IllegalStateException("tea is required");
            return new Order(this);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Order.Builder().tea("masala chai").cups(2).extraHot().build());
        System.out.println(new Order.Builder().tea("ginger chai").takeaway().build());
        Order c = new Order.Builder().cups(3).build();   // forgot the tea
    }
}

Output:

2 x masala chai, extra hot, dine-in
1 x ginger chai, takeaway
Exception in thread "main" java.lang.IllegalStateException: tea is required
    at Order$Builder.build(Main.java:17)
    at Main.main(Main.java:26)
  • Order.Builder holds the values, with defaults (one cup).
  • Each setter has a name and returns this, so calls chain: new Order.Builder().tea("masala chai").cups(2).extraHot().build().
  • build() checks the object is complete, then calls Order's private constructor, so an incomplete Order can never exist. Order's fields are final: the object is immutable.
  • StringBuilder (episode 10) works in this chained style; many libraries use builders (for example HttpRequest.newBuilder() in java.net.http).

4. Observer: tell many listeners

Real-life example: the ready bell. Ravi rings a bell; whoever cares (the screen, the customer, the delivery rider) listens; anyone can stop listening.

class Screen { void show(int token) { System.out.println("Screen: token " + token + " is ready"); } }
class Sms    { void send(int token) { System.out.println("SMS: your order " + token + " is ready"); } }

class Kitchen {
    Screen screen = new Screen();
    Sms sms = new Sms();
    // now the delivery app wants to know too: edit Kitchen AGAIN

    void orderReady(int token) {
        screen.show(token);
        sms.send(token);
    }
}

public class Main {
    public static void main(String[] args) {
        new Kitchen().orderReady(17);
    }
}

Output:

Screen: token 17 is ready
SMS: your order 17 is ready

It works, but every new listener (the delivery app) means editing Kitchen again: the kitchen knows everyone.

import java.util.*;

interface OrderListener { void ready(int token); }

class Kitchen {
    private final List<OrderListener> listeners = new ArrayList<>();
    void subscribe(OrderListener l)   { listeners.add(l); }
    void unsubscribe(OrderListener l) { listeners.remove(l); }
    void orderReady(int token) {
        for (OrderListener l : listeners) l.ready(token);
    }
}

public class Main {
    public static void main(String[] args) {
        Kitchen kitchen = new Kitchen();
        kitchen.subscribe(t -> System.out.println("Screen: token " + t + " is ready"));
        kitchen.subscribe(t -> System.out.println("SMS: your order " + t + " is ready"));
        OrderListener delivery = t -> System.out.println("Delivery app: pick up order " + t);
        kitchen.subscribe(delivery);

        kitchen.orderReady(17);
        kitchen.unsubscribe(delivery);                // the rider has gone home
        kitchen.orderReady(18);
    }
}

Output:

Screen: token 17 is ready
SMS: your order 17 is ready
Delivery app: pick up order 17
Screen: token 18 is ready
SMS: your order 18 is ready
  • The subject (Kitchen) keeps a list of observers (OrderListener) and notifies all of them; it doesn't know who they are.
  • OrderListener has one method, so each listener can be a lambda (episode 36).
  • Unsubscribe listeners you no longer need: a subject holding old listeners keeps them in memory forever (a memory leak, episode 43).
  • Observer is behind GUI button clicks, event systems, and publish/subscribe messaging.

5. Strategy: swap a rule at run time

Real-life example: the offer board. The cashier's way of adding up never changes; today's offer card slots in and is swapped tomorrow.

public class Main {
    static int total(int cups, String offer) {
        int sum = cups * 15;
        if (offer.equals("bulk")) {
            if (cups >= 10) sum = sum - sum / 10;
        } else if (offer.equals("happy hour")) {
            sum = sum - sum / 5;
        } else if (offer.equals("diwali")) {
            sum = sum - 20;
        } else if (offer.equals("student")) {
            sum = sum - cups * 2;
        }
        // ...and next week, another else-if
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(total(10, "bulk"));
        System.out.println(total(4, "happy hour"));
        System.out.println(total(4, "Happy Hour"));
    }
}

Output:

135
48
60

"Happy Hour" in capitals silently gets no discount (60), and this method grows with every offer.

interface Pricing { int apply(int cups, int sum); }

class Bill {
    private Pricing pricing = (cups, sum) -> sum;         // normal price
    void setPricing(Pricing p) { pricing = p; }
    int total(int cups) { return pricing.apply(cups, cups * 15); }
}

public class Main {
    public static void main(String[] args) {
        Pricing bulk      = (cups, sum) -> cups >= 10 ? sum - sum / 10 : sum;
        Pricing happyHour = (cups, sum) -> sum - sum / 5;
        Pricing diwali    = (cups, sum) -> Math.max(0, sum - 20);

        Bill bill = new Bill();
        System.out.println("Normal:     " + bill.total(4));
        bill.setPricing(happyHour);
        System.out.println("Happy hour: " + bill.total(4));
        bill.setPricing(bulk);
        System.out.println("Bulk:       " + bill.total(10));
        bill.setPricing(diwali);
        System.out.println("Diwali:     " + bill.total(3));
    }
}

Output:

Normal:     60
Happy hour: 48
Bulk:       135
Diwali:     25
  • The changing rule (Pricing) is behind an interface; Bill holds one and never changes.
  • Each offer is a lambda; a new offer is a new lambda, with no edits to Bill.
  • A Comparator passed to sort (episode 34) is a strategy for ordering.

Which pattern for which problem?

Problem Pattern Key idea
There must be exactly one of something Singleton private constructor, one instance
Creating objects by type is copied everywhere Factory one create() returning an interface
An object has many optional fields Builder named, chained steps, build() checks
Many parts must react to one event Observer subscribe, notify all, unsubscribe
A rule changes (offers, sorting, routing) Strategy the rule behind an interface, passed in
The plain code is already clear No pattern patterns fix real problems only

Common mistakes (and what you see)

Mistake What you see Fix
Two new TokenCounter() token 1 twice private constructor + getInstance()
new on a singleton error: TokenCounter() has private access in TokenCounter TokenCounter.getInstance()
A factory that returns null NullPointerException: Cannot invoke "Payment.pay(int)" because the return value of "Main.choose(String)" is null throw IllegalArgumentException
Swapped booleans in a long constructor 2 x masala chai, takeaway, sugar 1 (silently wrong) a Builder
Builder without a required field IllegalStateException: tea is required call .tea(...) before build()
Offers chosen by string "Happy Hour" gives 60, no discount, no error Strategy objects
Patterns everywhere lots of classes for simple code use a pattern only for a real problem

Mini project: an order pipeline

Combine them: TokenCounter (Singleton) gives each order a token; PaymentFactory (Factory) creates the payment; Order.Builder (Builder) builds the order; the Kitchen (Observer) announces "ready" to the screen and SMS; the Bill uses the current Pricing (Strategy). Each piece above runs as shown; put them in one program and print: token, order, bill, payment, and the ready messages.

Practice

1. Make TokenCounter an enum singleton.

Solution
enum TokenCounter {
    INSTANCE;
    private int next = 1;
    int nextToken() { return next++; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Token " + TokenCounter.INSTANCE.nextToken());
        System.out.println("Token " + TokenCounter.INSTANCE.nextToken());
    }
}

Output:

Token 1
Token 2

2. Add a Wallet payment to the factory.

Solution
interface Payment { String pay(int amount); }
class Upi    implements Payment { public String pay(int a) { return "Rs " + a + " by UPI"; } }
class Card   implements Payment { public String pay(int a) { return "Rs " + a + " by card"; } }
class Cash   implements Payment { public String pay(int a) { return "Rs " + a + " in cash"; } }
class Wallet implements Payment { public String pay(int a) { return "Rs " + a + " from the wallet"; } }

class PaymentFactory {
    static Payment create(String type) {
        return switch (type.toLowerCase()) {
            case "upi"    -> new Upi();
            case "card"   -> new Card();
            case "cash"   -> new Cash();
            case "wallet" -> new Wallet();
            default -> throw new IllegalArgumentException("Unknown payment type: " + type);
        };
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(PaymentFactory.create("Wallet").pay(60));
    }
}

Output:

Rs 60 from the wallet

Only one class and one case were added; callers didn't change.

3. Add a size (SMALL, LARGE) to the Order builder, defaulting to SMALL.

Solution
class Order {
    enum Size { SMALL, LARGE }
    private final String tea; private final int cups; private final Size size;
    private Order(Builder b) { tea = b.tea; cups = b.cups; size = b.size; }
    public String toString() { return cups + " x " + size + " " + tea; }

    static class Builder {
        private String tea; private int cups = 1; private Size size = Size.SMALL;
        Builder tea(String t)  { tea = t; return this; }
        Builder cups(int n)    { cups = n; return this; }
        Builder size(Size s)   { size = s; return this; }
        Order build() {
            if (tea == null) throw new IllegalStateException("tea is required");
            if (cups < 1) throw new IllegalStateException("cups must be at least 1");
            return new Order(this);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Order.Builder().tea("masala chai").size(Order.Size.LARGE).cups(2).build());
        System.out.println(new Order.Builder().tea("ginger chai").build());
    }
}

Output:

2 x LARGE masala chai
1 x SMALL ginger chai

4. A student offer strategy: Rs 2 off per cup.

Solution
interface Pricing { int apply(int cups, int sum); }

class Bill {
    private Pricing pricing = (cups, sum) -> sum;
    void setPricing(Pricing p) { pricing = p; }
    int total(int cups) { return pricing.apply(cups, cups * 15); }
}

public class Main {
    public static void main(String[] args) {
        Pricing student = (cups, sum) -> sum - cups * 2;     // Rs 2 off per cup
        Bill bill = new Bill();
        bill.setPricing(student);
        System.out.println("Student, 4 cups: " + bill.total(4));
    }
}

Output:

Student, 4 cups: 52

4 cups: 60 - 8 = 52.

Quick quiz

List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Arjun"));
names.sort(Comparator.comparing(String::length));
names.sort(Comparator.naturalOrder());

Which pattern is this? A) Singleton B) Builder C) Strategy D) Observer

Answer

C) Strategy. sort stays the same; the Comparator is the swappable ordering rule. Running it prints:

[Ravi, Asha, Arjun]
[Arjun, Asha, Ravi]

Interview questions

  1. What is a design pattern? A named, reusable solution to a common design problem; GoF described 23 in three groups (creational, structural, behavioral).
  2. How do you make a thread-safe singleton? A private static final instance (created at class loading), an enum singleton, or the holder-class idiom. Avoid unsynchronized lazy if (instance == null) creation with threads.
  3. Why is Singleton sometimes called an anti-pattern? It's global state: hidden dependencies and shared state make testing and change harder.
  4. Factory vs new? A factory hides which concrete class is created, centralises creation, and lets callers depend on an interface.
  5. When would you use a Builder? Many parameters, especially optional ones or several of the same type; it gives readable, validated, often immutable objects.
  6. Explain Observer with an example. A subject keeps a list of listeners and notifies them of events, e.g. button click listeners.
  7. Strategy vs if-else? Strategy puts each rule in its own object behind an interface; adding a rule means adding a class or lambda, not editing a growing method.
  8. Which patterns do lambdas simplify? Strategy, Observer (and Command): any pattern built around a one-method interface.

Glossary

Term Meaning
Design pattern a named, proven solution to a recurring design problem
Gang of Four (GoF) the four authors of the 1994 book Design Patterns
Creational / structural / behavioral the three groups of GoF patterns
Singleton a class with exactly one instance and one way to reach it
Global state data any part of the program can read and change
Dependency injection passing an object to the code that needs it instead of it grabbing a global one
Factory a method or class that creates objects for you, returning an interface
Builder a helper object that builds a complex object step by step
Telescoping constructor a constructor with a long list of parameters
Method chaining calls like a().b().c(), each returning this
Observer an object that subscribes to another to be told about events
Subject the object observers subscribe to
Subscribe / unsubscribe start / stop listening
Strategy a swappable rule behind an interface
Functional interface an interface with one abstract method, so a lambda can implement it

Summary

  • A design pattern is a named fix for a problem that keeps coming back.
  • Singleton: private constructor and one instance; use sparingly, it's global state.
  • Factory: one place that says new, returns an interface, fails loudly on unknown types.
  • Builder: named, chained steps with defaults, and checks in build().
  • Observer: subscribe, notify all, unsubscribe; listeners can be lambdas.
  • Strategy: a changing rule behind an interface, passed in and swapped at run time.
  • Use a pattern only for a real problem.
  • Next episode: DSA 1: Big-O, arrays, two pointers and the sliding window.