Java · Module 12 · Lesson 31 min read

Design Patterns

What are design patterns?

Reusable solutions to common design problems. They give teams a shared vocabulary: say "use a Builder here" and everyone knows what you mean.

Singleton — only one instance

Java
public enum AppConfig {
    INSTANCE;
    String apiUrl = "https://api.example.com";
}
AppConfig.INSTANCE.apiUrl;

An enum is the simplest thread-safe singleton. Use it for things like config or loggers. ⚠️ Overusing singletons makes testing harder.

Factory — let a method choose the class

Java
static Shape create(String type) {
    return switch (type) {
        case "circle" -> new Circle(1);
        case "square" -> new Square(1);
        default -> throw new IllegalArgumentException(type);
    };
}

Callers don't need to know which class is created.

Builder — many optional settings

Java
Pizza p = new Pizza.Builder("Large")
    .cheese(true)
    .topping("Mushroom")
    .build();

Much clearer than a constructor with 8 parameters.

Observer — notify subscribers

When one object changes, all its listeners are told automatically. Think YouTube subscriptions, button click listeners, or Flutter's ChangeNotifier.

Strategy — swap behaviour at runtime

Java
interface Discount { double apply(double price); }
Discount none = p -> p;
Discount sale = p -> p * 0.8;
checkout(cart, sale);

Use them wisely 🧠

Patterns solve specific problems. Don't add them "just because". Simple code that works beats clever code nobody understands.

Example

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

public class Pizza {
    private final String size;
    private final boolean cheese;
    private final List<String> toppings;

    private Pizza(Builder b) {
        this.size = b.size;
        this.cheese = b.cheese;
        this.toppings = List.copyOf(b.toppings);
    }

    public static class Builder {
        private final String size;              // required
        private boolean cheese = false;         // optional
        private final List<String> toppings = new ArrayList<>();

        public Builder(String size) { this.size = size; }
        public Builder cheese(boolean c) { this.cheese = c; return this; }
        public Builder topping(String t) { toppings.add(t); return this; }
        public Pizza build() { return new Pizza(this); }
    }

    @Override
    public String toString() {
        return size + " pizza, cheese=" + cheese + ", toppings=" + toppings;
    }

    public static void main(String[] args) {
        Pizza p = new Pizza.Builder("Large").cheese(true)
                     .topping("Mushroom").topping("Olive").build();
        System.out.println(p);
        // Large pizza, cheese=true, toppings=[Mushroom, Olive]
    }
}