← Java roadmap

Topic 18 of 30 · Expert

Design Patterns & SOLID

Singleton, Factory, Builder, Strategy and SOLID principles.

Concept

SOLID: Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion — guidelines for maintainable OOP.

Creational patterns: Singleton (one instance), Factory (create by type), Builder (many optional fields). Behavioural: Strategy (swap algorithms), Observer (publish/subscribe).

In interviews, explain the problem a pattern solves before writing code.

Code (Java 21)

// Thread-safe lazy singleton (holder idiom)
class Config {
    private Config() {}
    private static class Holder { static final Config INSTANCE = new Config(); }
    static Config get() { return Holder.INSTANCE; }
}

// Strategy
interface Discount { double apply(double p); }
class Festive implements Discount { public double apply(double p) { return p * 0.8; } }
class Checkout {
    private final Discount d;
    Checkout(Discount d) { this.d = d; }   // dependency injected
    double total(double p) { return d.apply(p); }
}

Remember

  • Enum singletons are serialization-safe.
  • Program to interfaces, not implementations.
  • Builder avoids telescoping constructors.

Interview questions

How do you make a thread-safe singleton?

Use an enum, the static holder idiom, or double-checked locking with a volatile field.

Explain the Liskov Substitution Principle.

A subclass must be usable wherever its parent is expected without breaking behaviour — e.g. Square extending Rectangle often violates it.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Design Patterns & SOLID” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.