Reading history

Design Patterns in Java: Singleton, Builder, Factory, Strategy, Observer

6 min read 0 views

Learn five essential design patterns in modern Java with runnable examples: Singleton, Builder, Factory, Strategy and Observer, and when to use each.

Design patterns are proven, reusable answers to problems that keep coming up in object-oriented code: “there should be only one of these”, “this object has too many optional settings”, “the rule should be swappable”, “these parts must be told when something changes”. This lesson builds five of the most useful patterns in plain, modern Java: Singleton, Builder, Factory, Strategy and Observer.

In this lesson you will learn

  • Singleton: one shared instance
  • Builder: readable construction with many options
  • Factory: one place that decides which class to create
  • Strategy: swappable behaviour, often just a lambda
  • Observer: notifying listeners when something changes

You should know classes, interfaces, static and final and lambdas.

Creating Objects: Singleton, Builder, Factory

import java.util.ArrayList;
import java.util.List;

public class Main {
    // Singleton: exactly one shared instance
    static final class AppConfig {
        private static final AppConfig INSTANCE = new AppConfig();
        private final String currency = "BDT";
        private AppConfig() { }                       // nobody else can call new
        static AppConfig get() { return INSTANCE; }
        String currency() { return currency; }
    }

    // Builder: readable construction of an object with many optional parts
    static final class Pizza {
        private final String size;
        private final List<String> toppings;
        private final boolean extraCheese;
        private Pizza(Builder b) { size = b.size; toppings = List.copyOf(b.toppings); extraCheese = b.extraCheese; }
        @Override public String toString() {
            return size + " pizza with " + toppings + (extraCheese ? " + extra cheese" : "");
        }
        static class Builder {
            private final String size;
            private final List<String> toppings = new ArrayList<>();
            private boolean extraCheese;
            Builder(String size) { this.size = size; }
            Builder topping(String t) { toppings.add(t); return this; }
            Builder extraCheese() { extraCheese = true; return this; }
            Pizza build() { return new Pizza(this); }
        }
    }

    // Factory: one method decides which class to create
    interface Notifier { String send(String msg); }
    static class SmsNotifier implements Notifier { public String send(String m) { return "SMS: " + m; } }
    static class EmailNotifier implements Notifier { public String send(String m) { return "Email: " + m; } }
    static Notifier notifierFor(String channel) {
        return switch (channel) {
            case "sms" -> new SmsNotifier();
            case "email" -> new EmailNotifier();
            default -> throw new IllegalArgumentException("Unknown channel: " + channel);
        };
    }

    public static void main(String[] args) {
        System.out.println("Same config object? " + (AppConfig.get() == AppConfig.get())
                + ", currency " + AppConfig.get().currency());

        Pizza p = new Pizza.Builder("Large").topping("chicken").topping("onion").extraCheese().build();
        System.out.println(p);

        for (String ch : new String[] {"sms", "email"}) {
            System.out.println(notifierFor(ch).send("Your order has shipped"));
        }
    }
}

Output

Same config object? true, currency BDT
Large pizza with [chicken, onion] + extra cheese
SMS: Your order has shipped
Email: Your order has shipped
  • Singleton: the constructor is private, so no other code can call new AppConfig(). The single instance is created once in a static final field, which is also thread-safe. Both calls to get() return the same object.
  • Builder: instead of a constructor with many parameters, such as new Pizza("Large", list, true, false, null), each setting has a named method. Each method returns the builder, so the calls chain. build() creates the final, unchangeable Pizza.
  • Factory: notifierFor is the only code that knows which class handles which channel. Callers just ask for “sms” and get a Notifier. Adding WhatsApp later means changing one method, not every caller.

Changing Behaviour: Strategy and Observer

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class Main {
    // Strategy: swap the algorithm (here, the discount rule) at run time
    interface DiscountStrategy { double apply(double amount); }

    static class Checkout {
        private DiscountStrategy strategy = amount -> amount;     // no discount by default
        void setStrategy(DiscountStrategy s) { strategy = s; }
        double total(double amount) { return strategy.apply(amount); }
    }

    // Observer: listeners are told when something happens
    static class OrderTracker {
        private final List<Consumer<String>> listeners = new ArrayList<>();
        void subscribe(Consumer<String> listener) { listeners.add(listener); }
        void updateStatus(String status) {
            for (Consumer<String> l : listeners) l.accept(status);
        }
    }

    public static void main(String[] args) {
        Checkout c = new Checkout();
        System.out.println("Normal price: " + c.total(2000));
        c.setStrategy(amount -> amount * 0.90);                               // 10% off
        System.out.println("Eid sale:     " + c.total(2000));
        c.setStrategy(amount -> amount >= 1500 ? amount - 250 : amount);      // flat 250 off
        System.out.println("Coupon:       " + c.total(2000));

        OrderTracker tracker = new OrderTracker();
        tracker.subscribe(s -> System.out.println("  [customer app] Order is now " + s));
        tracker.subscribe(s -> System.out.println("  [warehouse]    Status changed to " + s));
        tracker.updateStatus("PACKED");
        tracker.updateStatus("SHIPPED");
    }
}

Output

Normal price: 2000.0
Eid sale:     1800.0
Coupon:       1750.0
  [customer app] Order is now PACKED
  [warehouse]    Status changed to PACKED
  [customer app] Order is now SHIPPED
  [warehouse]    Status changed to SHIPPED
  • Strategy: Checkout does not contain any discount rules itself. It holds a DiscountStrategy and calls it. Swapping the strategy changes the total from 2,000 to 1,800 (10% off) or 1,750 (flat 250 off), without touching Checkout.
  • Because DiscountStrategy has one method, each strategy can be a lambda. In modern Java many patterns shrink to a functional interface plus lambdas.
  • Observer: the order tracker keeps a list of listeners and calls each one when the status changes. The tracker does not know who is listening, so you can add a new listener, such as an SMS sender, without changing it.

When to Use Which

PatternProblem it solvesEveryday Java example
SingletonExactly one shared objectRuntime.getRuntime()
BuilderObjects with many optional settingsStringBuilder, HttpRequest.newBuilder()
FactoryHide which concrete class is createdList.of(...), Executors.newFixedThreadPool(4)
StrategySwap an algorithm or rulePassing a Comparator to sort
ObserverTell many parts that something happenedButton click listeners in GUIs

Common Mistakes

  1. Using Singletons for everything. They act like global variables, make testing harder and hide dependencies. Pass objects in where you can.
  2. Adding a pattern before you need it. A simple constructor is better than a builder for a class with two fields.
  3. Forgetting to remove observers that are no longer needed, which keeps them in memory.
  4. Writing a whole class hierarchy for a strategy that a lambda could express in one line.

Practice Exercises

Exercise 1. Add a “buy over 3,000, get 15% off” strategy and test it with 2,000 and 4,000.

Show answer
c.setStrategy(amount -> amount > 3000 ? amount * 0.85 : amount);
System.out.println(c.total(2000));   // 2000.0
System.out.println(c.total(4000));   // 3400.0

Exercise 2. Add a check to the pizza builder so that build() throws an exception if more than 5 toppings were added.

Show answer
Pizza build() {
    if (toppings.size() > 5)
        throw new IllegalStateException("At most 5 toppings");
    return new Pizza(this);
}

Checking in build() means a half-configured object can never escape.

Frequently Asked Questions

Where do these pattern names come from?

They were made popular by the 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides, often called the “Gang of Four”. The book describes 23 patterns; the five here are among the most used.

Is an enum a good way to make a Singleton?

Yes. enum Config { INSTANCE; ... } is a short, thread-safe singleton that also cannot be duplicated through serialization or reflection.

Summary

  • Singleton: private constructor, one static instance.
  • Builder: named, chainable settings, then build().
  • Factory: one method chooses the concrete class.
  • Strategy and Observer often become lambdas and listener lists in modern Java.

Next: Java Collections Framework Overview.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *