GamifiedGamified challengesPracticeRaceLeaderboardPricing

Learn data structures by watching them move, then doing it yourself. Press M anytime to toggle sound.

A product of Amypo Technologies, Coimbatore.

Learn

  • All topics
  • Learning path
  • How it works
  • About dotprep

Practice

  • Practice arena
  • Daily challenge
  • Gamified challenges
  • Race mode
  • Leaderboard

Interview prep

  • Java interview
  • Coding questions
  • Company questions
  • System design
  • Jobs & careers

You

  • Dashboard
  • Settings
  • Pricing
  • Create account

© 2026 dotprep

Content last updated 20 November 2026

GamifiedGamified challengesPracticeRaceLeaderboardPricing
Java interviewDesign patterns & SOLID

Design patterns & SOLID

SOLID principles and the patterns interviewers ask for most: Singleton, Factory, Builder, Strategy, Observer, Decorator.

intermediate 18 min read 6 interview questions

On this page

1/6
  1. 01SOLID principles
  2. 02Singleton
  3. 03Factory and Builder
  4. 04Strategy, Observer and Decorator
  5. 05Interview questions
  6. 06Quick check
Back to top

SOLID principles

PrincipleIn one line
Single responsibilityA class has one reason to change.
Open/closedOpen for extension, closed for modification: add behaviour with new classes, not by editing old ones.
Liskov substitutionA subclass must work anywhere its parent is expected, without surprises.
Interface segregationMany small interfaces beat one fat interface.
Dependency inversionDepend on abstractions (interfaces), and receive dependencies from outside (injection).

Singleton

Exactly one instance, globally accessible. Thread-safe options:

java
// 1. Holder idiom: lazy and thread-safe without locks
public final class Config {
private Config() {}
private static class Holder { static final Config INSTANCE = new Config(); }
public static Config get() { return Holder.INSTANCE; }
}
// 2. Enum: also safe against reflection and serialization
public enum Registry { INSTANCE; void register(String k) { } }
// 3. Double-checked locking needs volatile
private static volatile Cache instance;
public static Cache get() {
if (instance == null) synchronized (Cache.class) {
if (instance == null) instance = new Cache();
}
return instance;
}

Singletons are global state: they make testing harder. Prefer one instance managed by a dependency-injection container.

Factory and Builder

java
interface Notifier { void send(String msg); }
class EmailNotifier implements Notifier { public void send(String m) { } }
class SmsNotifier implements Notifier { public void send(String m) { } }
class NotifierFactory { // callers don't name concrete classes
static Notifier of(String channel) {
return switch (channel) {
case "email" -> new EmailNotifier();
case "sms" -> new SmsNotifier();
default -> throw new IllegalArgumentException(channel);
};
}
}
java
Pizza p = new Pizza.Builder("large") // Builder: readable construction of many optional parts
.cheese(true)
.topping("olives")
.build();

Strategy, Observer and Decorator

  • Strategy: swap an algorithm at run time behind one interface. Comparator is a strategy for sorting.
  • Observer: subjects notify registered listeners of changes (event listeners, pub-sub).
  • Decorator: wrap an object to add behaviour without subclassing. new BufferedReader(new FileReader(f)) decorates a reader.
java
interface Discount { long apply(long price); }
class NoDiscount implements Discount { public long apply(long p) { return p; } }
class Percent implements Discount {
final int pct; Percent(int pct) { this.pct = pct; }
public long apply(long p) { return p * (100 - pct) / 100; }
}
class Checkout {
private final Discount discount; // strategy injected
Checkout(Discount d) { discount = d; }
long total(long price) { return discount.apply(price); }
}

Interview questions

Try answering out loud first, then open the model answer.

Q1Explain the SOLID principles with examples.intermediate

S: a ReportService shouldn't also format emails. O: add a new Discount class rather than editing an if-chain. L: a Square subclass breaking Rectangle.setWidth expectations violates it. I: split Machine into Printer and Scanner. D: OrderService depends on a PaymentGateway interface passed into its constructor.

Q2How do you write a thread-safe singleton?intermediate

Use an enum, or the holder-class idiom (the JVM initializes the nested class lazily and thread-safely), or double-checked locking with a volatile field. A plain lazy check without synchronization can create two instances.

Q3Factory vs Builder?beginner

A factory decides which class to create and hides the concrete type. A builder deals with how to construct one complex object step by step, especially with many optional parameters, avoiding telescoping constructors.

Q4Where do you see the Decorator pattern in the JDK?intermediate

Java I/O: BufferedInputStream(new FileInputStream(...)), Collections.unmodifiableList(list), Collections.synchronizedMap(map). Each wraps an object of the same interface and adds behaviour.

Q5Strategy vs State pattern?advanced

Both delegate to an interchangeable object. In Strategy the client picks the algorithm and it usually stays fixed. In State the object switches its own state object as it moves through a lifecycle (e.g. an order going Pending → Paid → Shipped).

Q6What is dependency injection?intermediate

An object receives its collaborators from outside (usually through the constructor) instead of creating them. It decouples code from concrete classes, makes testing with fakes easy, and is how Spring wires beans.

Quick check

Question 1

1.Comparator passed to sort() is an example of…

Question 2

2.Which pattern fits a class with many optional constructor parameters?

Question 3

3.Double-checked locking for a singleton needs the field to be…

Question 4

4.The "D" in SOLID stands for…

0 of 4 answered

JVM internals & garbage collection
Log inStart free