Interview Questions

10 Common Java Design Patterns Interview Questions & Answers

Author: Interview Questions Posted 5 days ago 52 min read

Design patterns are reusable solutions to common software design problems. In Java interviews, questions typically focus on Gang of Four (GoF) patterns, their real-world JDK implementations, thread-safety concerns, and trade-offs.


1. What are Design Patterns, and how are they categorized?

Design patterns are proven, standardized templates for solving recurring architectural and object-oriented design problems. They improve code maintainability, readability, and scalability.

According to the Gang of Four (GoF), design patterns are divided into three categories:

  • Creational Patterns: Deal with object creation mechanisms, decoupling a system from how its objects are created (e.g., Singleton, Factory Method, Abstract Factory, Builder, Prototype).
  • Structural Patterns: Deal with object and class composition to form larger structures while keeping them flexible (e.g., Adapter, Decorator, Proxy, Facade, Composite).
  • Behavioral Patterns: Deal with communication and responsibility assignment between objects (e.g., Observer, Strategy, Command, Template Method, State).


2. How do you implement a thread-safe Singleton in Java, and how can it be broken?

A Singleton ensures a class has only one instance and provides a global point of access to it.

Best Implementations

  • Bill Pugh Singleton (Initialization-on-demand holder idiom): Lazy-loaded and thread-safe without synchronization overhead, relying on JVM class-loading guarantees.
public class BillPughSingleton {
    private BillPughSingleton() {}

    private static class SingletonHelper {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}
  • Enum Singleton (Recommended by Joshua Bloch): Inherently thread-safe and immune to reflection and serialization attacks.
public enum EnumSingleton {
    INSTANCE;

    public void doSomething() {
        // business logic
    }
}

How Singleton Can Be Broken (and Prevented)

  • Reflection: Calling setAccessible(true) on the private constructor. Fix: Throw an exception inside the constructor if an instance already exists, or use an Enum.
  • Serialization/Deserialization: Deserializing creates a new instance. Fix: Implement readResolve() to return the existing INSTANCE.
  • Cloning: Calling clone() if the class implements Cloneable. Fix: Override clone() and throw CloneNotSupportedException.

3. What is the difference between the Factory Method and Abstract Factory patterns?

Feature Factory Method Abstract Factory
Scope Creates one product type. Creates families of related or dependent products.
Mechanism Uses inheritance and subclassing (overrides a factory method). Uses object composition (passes a factory object to the client).
Example Logistics class with createTransport() returning Truck or Ship. GUIFactory creating matching Button, Checkbox, and Scrollbar for Windows or macOS.
JDK Example Calendar.getInstance(), NumberFormat.getInstance() DocumentBuilderFactory.newInstance(), TransformerFactory.newInstance()

4. When should you use the Builder pattern instead of telescoping constructors?

The Builder pattern separates the construction of a complex object from its representation. Use it when:

  • A class has many parameters (typically 4 or more), especially when several are optional.
  • You want to create immutable objects without forcing callers to pass null for optional fields in a giant constructor (the telescoping constructor anti-pattern).
  • Parameter validation is required before the object is fully constructed.
public class User {
    private final String username; // required
    private final String email;    // optional
    private final int age;         // optional

    private User(Builder builder) {
        this.username = builder.username;
        this.email = builder.email;
        this.age = builder.age;
    }

    public static class Builder {
        private final String username;
        private String email = "";
        private int age = 0;

        public Builder(String username) {
            this.username = username;
        }

        public Builder email(String email) {
            this.email = email;
            return this;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}

  • JDK Example: StringBuilder, Stream.Builder, HttpRequest.newBuilder().

5. How do the Strategy and State patterns differ?

Both patterns share the exact same UML structure (composition + delegation to an interface), but their intent differs:

  • Strategy Pattern: Encapsulates interchangeable algorithms. The client explicitly chooses and injects the strategy (e.g., passing CreditCardPayment vs. PayPalPayment to a ShoppingCart). Strategies are usually unaware of each other.
  • State Pattern: Allows an object to alter its behavior when its internal state changes. State transitions are managed internally by the context or the states themselves (e.g., an Order transitioning from New $\rightarrow$ Paid $\rightarrow$ Shipped $\rightarrow$ Delivered). States often know about neighboring states.

6. Explain the Decorator pattern and how it is used in the Java I/O API.

The Decorator pattern attaches additional responsibilities to an object dynamically at runtime by wrapping it inside decorator objects that implement the same interface. It provides a flexible alternative to subclassing for extending functionality (avoiding class explosion).

Java I/O Example

java.io relies heavily on Decorators around core streams (InputStream, OutputStream, Reader, Writer):

// FileInputStream is the concrete component.
// BufferedInputStream and DataInputStream are decorators adding buffering and primitive reading.
InputStream in = new DataInputStream(
                     new BufferedInputStream(
                         new FileInputStream("data.bin")));


7. What are the differences between Proxy, Decorator, and Adapter?

All three are structural wrapper patterns, but each serves a distinct purpose:

Pattern Interface Changed? Primary Intent
Adapter Yes Converts an incompatible interface into one the client expects (Arrays.asList(), InputStreamReader).
Decorator No (same interface) Dynamically adds new behavior/responsibilities to an object (Collections.unmodifiableList()).
Proxy No (same interface) Controls access to an object—for lazy loading, security, logging, caching, or remote RPC calls (Spring AOP, Hibernate lazy entities).

8. How does the Observer pattern work, and what are its pitfalls in Java?

The Observer pattern defines a one-to-many dependency where a Subject (publisher) maintains a list of Observers (subscribers) and notifies them automatically of any state changes.

Common Pitfalls

  • Memory Leaks (Lapsed Listener Problem): If a Subject holds strong references to Observers and observers are not explicitly unregistered, garbage collection cannot reclaim them. Mitigation: Use WeakReference or explicit lifecycle cleanup.
  • Cascading Updates / Performance Bottlenecks: Synchronous notification of many slow observers blocks the subject's thread. Mitigation: Dispatch events asynchronously via an ExecutorService or message queue.
  • Note on java.util.Observable: Deprecated since Java 9 because it was a concrete class (preventing multiple inheritance) and lacked type safety. Modern Java code uses PropertyChangeListener, Flow API (Reactive Streams), or event buses like Spring's ApplicationEventPublisher.

9. What is the Template Method pattern, and how does it apply the Hollywood Principle?

The Template Method pattern defines the skeleton of an algorithm in an abstract base class, deferring specific steps to subclasses without changing the algorithm's overall structure.

It embodies the Hollywood Principle ("Don't call us, we'll call you"): the high-level base class controls the execution flow and calls the low-level subclass hook methods at the appropriate moments, rather than subclasses calling the parent.

public abstract class DataProcessor {
    // Template method marked final so subclasses cannot alter the workflow
    public final void process() {
        readData();
        transformData();
        saveData();
    }

    protected abstract void readData();
    protected abstract void transformData();

    // Concrete default step (or optional hook)
    protected void saveData() {
        System.out.println("Saving to default database...");
    }
}

  • JDK / Framework Examples: HttpServlet (service() calls doGet(), doPost()), AbstractList, Spring's JdbcTemplate.

10. What is the SOLID Dependency Inversion Principle (DIP), and which design patterns rely on it?

Dependency Inversion Principle: High-level modules should not depend on low-level modules; both should depend on abstractions (interfaces or abstract classes).

Patterns Driven by DIP

  • Factory Method & Abstract Factory: High-level business logic depends on product interfaces while factories supply concrete implementations.
  • Strategy: The context depends on a Strategy interface rather than concrete algorithm classes.
  • Observer: The subject notifies an Observer interface without knowing concrete listener types.
  • Adapter & Proxy: Clients interact with target interfaces decoupled from underlying implementations.