Stop 05 · Inheritance, Polymorphism & InterfacesTopics · 9/9

Design Patterns (Singleton, Factory, Builder, Strategy)

Part of the Java Roadmap

In short

Design patterns are names for solutions developers keep rediscovering. Knowing them lets you read Spring and other libraries faster and explain your design in one word during interviews.

Design patterns are proven solutions to common design problems. Singleton ensures one instance, Factory hides object creation, Builder constructs complex objects step by step, and Strategy swaps behaviour at runtime.

The jaadu, behind a sweet shop counter, packs a gift box layer by layer with different sweets from neat trays.

Think of it like this

A halwai's recipe book

A sweet shop doesn't invent a new method each Diwali. There's one head halwai (Singleton). You ask the counter for "1 kg kaju katli" and don't see how it's made (Factory). Custom gift boxes are packed step by step (Builder). And the same sweet can be packed with a festive or a regular discount (Strategy). Patterns are those tried recipes.

Watch it happen

Four patterns, two families

Design patterns
Creational
Behavioural
Singleton
Factory
Builder
Strategy

1/3Creational patterns are about how objects get created.

The big ideas

What you need to know

Singleton

Exactly one instance, like an app-wide config. The simplest safe version is enum AppConfig { INSTANCE; }. Use sparingly, as global state is hard to test.

Factory

A method like DiscountFactory.forCode("DIWALI10") returns the right object, so callers never write new for each type.

Builder

Pizza.builder().size("large").topping("paneer").build() beats a constructor with eight confusing parameters.

Strategy

Put each algorithm behind one interface and pass the one you want, like choosing a fastest or no-toll route in a maps app.

See it in code

Walk through the code

java
1interface DiscountStrategy {2    long apply(long amount);3}4 5class NoDiscount implements DiscountStrategy {6    @Override7    public long apply(long amount) { return amount; }8}9 10class FestiveDiscount implements DiscountStrategy {11    @Override12    public long apply(long amount) { return amount * 90 / 100; }13}14 15final class DiscountFactory {16    static DiscountStrategy forCode(String code) {17        return switch (code) {18            case "DIWALI10" -> new FestiveDiscount();19            default -> new NoDiscount();20        };21    }22}23 24class Cart {25    private DiscountStrategy discount = new NoDiscount();26 27    void applyCode(String code) {28        discount = DiscountFactory.forCode(code);29    }30 31    long payable(long subtotal) {32        return discount.apply(subtotal);33    }34}

1/4Strategy: one interface, many interchangeable algorithms.

Cart cart = new Cart(); cart.applyCode("DIWALI10"); cart.payable(2000) returns 1800.

Save yourself the pain

Common mistakes

Oops

Making many classes Singletons because it's convenient to reach them from anywhere.

Do this instead

Singletons are global state and make testing hard. Prefer passing objects in through constructors.

Oops

Forcing a pattern into a tiny program to look professional.

Do this instead

Use a pattern when you feel the problem it solves, like a growing if-else chain that Strategy would clean up.

Oops

Writing a lazy Singleton with if (instance == null) and no thread safety.

Do this instead

Use an enum singleton or an eagerly created private static final instance. Both are thread-safe.

Your mission

Spot and apply a pattern

~30 min

Quick check

Your checkout has a long if-else that changes how tax is calculated per country. Which pattern fits best?

Go deeper

  1. 1Implement a thread-safe Singleton and learn why an enum is the simplest way.
  2. 2Use the Builder pattern for an Order class with many optional fields.
  3. 3Replace a long if-else chain for discount rules with the Strategy pattern.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge