Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsJava Design Patterns in Depth
✓ FreeAdvanced· 6 min read

Design Patterns Overview & Singleton — Interview Questions

The three GoF families and the patterns worth knowing cold, then Singleton in depth — purpose, thread-safe implementations, lazy initialisation, defending against serialization and reflection, and when to avoid it.

Published September 25, 2026


How to use this lesson

Pattern questions at this level are judged on when you'd use a pattern, and what it costs, not on reciting UML. For every pattern in this chapter, have one real example from your own systems ready, and one situation where you'd deliberately not use it.

Q1. What are the creational patterns?

Short answer: Creational patterns control how objects are created, decoupling clients from concrete classes:

  • Singleton: exactly one instance, with a global access point.
  • Factory Method: a method (often overridden or parameterised) decides which concrete class to create.
  • Abstract Factory: creates families of related objects that must be used together.
  • Builder: step-by-step construction of complex, often immutable, objects.
  • Prototype: create new objects by copying a configured instance.

Learn it in depth → Singleton Pattern

Q2. What are the structural patterns?

Short answer: Structural patterns deal with how classes and objects are composed:

  • Adapter: converts one interface into another that the client expects.
  • Bridge: separates an abstraction from its implementation, so both can vary independently.
  • Composite: treats individual objects and trees of objects uniformly.
  • Decorator: adds responsibilities dynamically, by wrapping.
  • Facade: a simple interface to a complex subsystem.
  • Proxy: a stand-in that controls access (lazy loading, remote calls, security, caching).
  • Flyweight: shares fine-grained objects, to save memory.

Learn it in depth → Adapter & Facade

Q3. What are the behavioural patterns?

Short answer: Behavioural patterns deal with communication and the division of responsibility between objects:

  • Chain of Responsibility: pass a request along handlers until one of them handles it.
  • Command: encapsulate a request as an object (queueing, undo, logging).
  • Observer: notify subscribers when state changes.
  • Strategy: swap algorithms at runtime.
  • Template Method: a fixed algorithm skeleton, with overridable steps.
  • State: behaviour changes with the object's internal state.
  • Iterator, Mediator, Memento, Visitor, Interpreter: the less common ones.

Key points to cover:

  • In interviews, the most frequently probed are Singleton, Factory, Builder, Strategy, Observer, Decorator, Proxy, Template Method, Adapter and Chain of Responsibility. Know where Spring and the JDK use each one.

Learn it in depth → Strategy Pattern

Q4. What is the Singleton pattern, and why is it useful?

Short answer: Singleton guarantees that a class has exactly one instance (per class loader), and provides a well-known access point. It's useful for truly process-wide, shared resources where several instances would be wrong or wasteful: a metrics registry, a configuration snapshot, a thread-safe cache, a hardware or device handle.

Key points to cover:

  • Note the difference between "one instance of a pool" and "one connection". A connection pool may be a singleton, but it manages many connections.
  • In Spring, the default singleton scope gives you one instance per container without static global state, which is the preferred approach.

Q5. How do you implement a thread-safe singleton?

Short answer: The three recommended forms:

// 1) Enum: simplest; thread-safe, serialization-safe and reflection-safe
public enum MetricsRegistry { INSTANCE; public void inc(String name) { /* … */ } }

// 2) Initialization-on-demand holder: lazy, lock-free, relies on the JVM's class-init guarantees
public final class Config {
    private Config() { }
    private static final class Holder { static final Config INSTANCE = new Config(); }
    public static Config getInstance() { return Holder.INSTANCE; }
}

// 3) Double-checked locking: lazy; volatile is REQUIRED
public final class Registry {
    private static volatile Registry instance;
    public static Registry getInstance() {
        Registry r = instance;
        if (r == null) {
            synchronized (Registry.class) {
                r = instance;
                if (r == null) instance = r = new Registry();
            }
        }
        return r;
    }
}

Common trap: double-checked locking without volatile. Reordering can let another thread see a non-null reference to an object that isn't fully constructed yet.

Q6. What is lazy initialisation in a singleton?

Short answer: Creating the instance on first use, rather than when the class loads. It's worth it when construction is expensive (loading large data, opening resources), and the singleton might not be needed at all. The holder idiom gives laziness for free, because the nested class initialises only when getInstance() first touches it.

Key points to cover:

  • Eager initialisation is often fine, and simpler: the class itself is only loaded when first used anyway. Laziness mainly matters when the class has other static members that are used earlier.
  • Beware of heavy work or I/O in lazy initialisers on request paths. The first request pays the cost, and failures surface in odd places. Consider warming up at startup.

Q7. How do you stop a singleton being broken by serialization or reflection?

Short answer:

  • Serialization: implement readResolve() returning the existing instance, and make the instance fields transient. Deserialization then discards the new copy.
  • Reflection: a private constructor alone does not stop reflection, because setAccessible(true) bypasses it. Add a guard that throws if an instance already exists, or better, use an enum. The JVM forbids reflective creation of enum instances.
  • Cloning: don't implement Cloneable, or override clone() to throw.
private Singleton() {
    if (Holder.INSTANCE != null) throw new IllegalStateException("already initialised");
}
private Object readResolve() { return Holder.INSTANCE; }

Common trap: "make the constructor private to prevent reflection". That's precisely what reflection bypasses.

Q8. When should you avoid the Singleton pattern?

Short answer: Most of the time, in application code:

  • Hidden dependencies: callers reach for X.getInstance() instead of declaring what they need.
  • Global mutable state: order-dependent bugs and test pollution (state leaks between tests, and it's hard to mock).
  • Concurrency hotspots: one contended object.
  • It doesn't scale across processes: "one per JVM" isn't "one per system".
  • Lifecycle inflexibility: it can't be reconfigured per tenant or per test.

Better: dependency injection with singleton scope (Spring beans), which gives one instance with explicit, mockable dependencies. For cluster-wide uniqueness (for example, one scheduler instance), use a distributed lock or leader election.

Follow-up questions this topic invites — and their answers

Q: Is a Spring singleton bean the same as the GoF Singleton? A: No. Spring guarantees one instance per application context, created and injected by the container. The class itself doesn't enforce uniqueness, and a test can create more instances.

Q: Can a singleton have multiple instances in one JVM? A: Yes, if the class is loaded by several class loaders (app servers, plugins), because each loader gets its own class and static state.

Q: Is the enum singleton lazy? A: The enum constant is created when the enum class is initialised, which happens on first use of the enum. So it's effectively lazy, unless other code touches the enum earlier.

Q: Which JDK classes follow the Singleton pattern? A: Runtime.getRuntime(), Desktop.getDesktop(), and System's static facilities (not a singleton instance, but global state). Many JDK "singletons" today are enum constants or cached immutable instances (Collections.emptyList()).

Previous

Class Loading, Reflection, Serialization & Idioms — Interview Questions

Next

Factory & Abstract Factory Patterns — Interview Questions

AI Tutor

Lesson: Design Patterns Overview & Singleton — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.