Autocoder

Design Patterns Interview Questions with Code

Last updated 2026-11-19

Interviewers ask about design patterns to see whether you recognise recurring problems and know the trade-off of each solution. The most-asked are Singleton, Factory, Builder, Observer, Strategy and Decorator. This page gives each in working code, with the situations where the pattern helps and where it hurts.

Patterns express the principles in SOLID questions, and they are applied in low-level design questions. Start with OOPs interview questions if the underlying ideas need revision, and use how to crack a low-level design interview for the round plan.

GroupsCreational, structural, behavioural
Most askedSingleton, Factory, Builder, Observer, Strategy, Decorator
Code inJava and Python

The three groups

How to answer "which pattern would you use"

State the force first: "I need to choose an algorithm at run time without if-else", then name the pattern, then the cost. Strategy fits that sentence, and the cost is an extra class per algorithm. Interviewers value the reasoning more than the name.

Design Patterns Interview Questions with Code: questions with worked answers

  1. 1

    What are design patterns and why use them?

    easy

    Design patterns are reusable, named solutions to commonly occurring design problems, described by the Gang of Four book with 23 patterns. They give teams a shared vocabulary ("use an observer here"), capture proven structures and encourage loose coupling. They are not code to copy but templates to adapt, and misapplied patterns add complexity without benefit.

  2. 2

    Write a thread-safe Singleton in Java and explain the options.

    medium

    Singleton ensures one instance with a global access point. Double-checked locking needs the field to be volatile so other threads never see a partially constructed object. The initialisation-on-demand holder idiom is simpler: the JVM guarantees the nested class loads lazily and thread-safely. A single-element enum is the most robust, also surviving serialization and reflection. The downside of all singletons is hidden global state, which makes testing difficult; prefer injecting a single shared instance.

    java
    public final class Config {
        private static volatile Config instance;
        private Config() { }
        public static Config get() {
            if (instance == null) {
                synchronized (Config.class) {
                    if (instance == null) instance = new Config();
                }
            }
            return instance;
        }
    }
    // Holder idiom
    class Registry {
        private Registry() { }
        private static class Holder { static final Registry I = new Registry(); }
        static Registry get() { return Holder.I; }
    }
  3. 3

    What is the Factory Method pattern, and how is it different from Abstract Factory?

    medium

    Factory Method defines a method for creating an object and lets subclasses or the method's logic decide which concrete class to return, so callers depend on the product interface only. Abstract Factory creates families of related objects, such as a UI toolkit factory that produces matching Button and Checkbox for Windows or macOS, guaranteeing that the products are compatible. A simple static factory with a switch is the common practical form; it is not one of the 23, but it is what most code uses.

    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 {
        static Notifier create(String type) {
            return switch (type) {
                case "email" -> new EmailNotifier();
                case "sms"   -> new SmsNotifier();
                default -> throw new IllegalArgumentException(type);
            };
        }
    }
  4. 4

    When do you use the Builder pattern?

    medium

    Use Builder when an object has many optional parameters, so a constructor would need telescoping overloads or a confusing list of nulls. The builder sets fields by name, can validate in build(), and produces an immutable object. Examples: StringBuilder, a HttpRequest builder, Lombok's @Builder. It adds a class and some boilerplate, so it is not worth it for objects with two or three fields.

    java
    class Pizza {
        private final String size; private final boolean cheese; private final boolean mushrooms;
        private Pizza(Builder b) { size = b.size; cheese = b.cheese; mushrooms = b.mushrooms; }
        static class Builder {
            private String size = "M"; private boolean cheese; private boolean mushrooms;
            Builder size(String s) { size = s; return this; }
            Builder cheese() { cheese = true; return this; }
            Builder mushrooms() { mushrooms = true; return this; }
            Pizza build() { return new Pizza(this); }
        }
    }
    // new Pizza.Builder().size("L").cheese().build();
  5. 5

    Explain the Observer pattern with code.

    medium

    A subject keeps a list of observers and notifies them when its state changes, so the subject does not know their concrete types. Use it for event systems, UI listeners and publish-subscribe within a process. Pitfalls: observers that are never unregistered cause memory leaks, notification order is not guaranteed, and a long chain of updates is hard to debug. Distributed equivalents use brokers; see message queues and Kafka questions.

    python
    class Stock:
        def __init__(self): self._observers = []; self._price = 0
        def subscribe(self, fn): self._observers.append(fn)
        def set_price(self, p):
            self._price = p
            for fn in self._observers: fn(p)
    
    s = Stock()
    s.subscribe(lambda p: print("alert:", p))
    s.set_price(101)    # alert: 101
  6. 6

    Explain the Strategy pattern and how it removes if-else chains.

    medium

    Strategy puts interchangeable algorithms behind a common interface and lets the context choose one at run time. A route planner can hold a RouteStrategy that is Fastest, Shortest or Cheapest, so adding one means a new class and no change to the planner. In Java 8 and later a functional interface and lambdas give a lighter version. Choose it when you have several variants of one behaviour that change independently of the client.

    java
    interface PricingStrategy { double price(double base); }
    class Checkout {
        private PricingStrategy strategy;
        Checkout(PricingStrategy s) { strategy = s; }
        double total(double base) { return strategy.price(base); }
    }
    // new Checkout(b -> b * 0.9).total(1000);   // 10 percent off
  7. 7

    Explain the Decorator pattern and how it differs from inheritance.

    medium

    A decorator wraps an object that has the same interface and adds behaviour before or after delegating, so features are layered at run time. Java's BufferedReader wrapping a FileReader is the standard example. Subclassing would need a class for every combination (MilkSugarCoffee, MilkCoffee), which explodes; decorators combine freely, in any order. The cost is many small objects and stack traces that go through several wrappers.

    java
    interface Coffee { double cost(); }
    class Plain implements Coffee { public double cost() { return 50; } }
    class Milk implements Coffee {
        private final Coffee inner;
        Milk(Coffee c) { inner = c; }
        public double cost() { return inner.cost() + 15; }
    }
    // new Milk(new Milk(new Plain())).cost()  ->  80
  8. 8

    What are Adapter and Facade? How do they differ?

    medium

    Adapter converts one interface into another that clients expect, so an incompatible class can be reused, such as wrapping a third-party payment SDK behind your PaymentGateway interface. Facade offers one simplified interface to a complex subsystem, such as OrderFacade.placeOrder() coordinating inventory, payment and shipping. Adapter changes an interface to fit; facade reduces an interface to the essentials. Neither adds new behaviour of its own.

  9. 9

    What is the Proxy pattern? Name its common forms.

    medium

    A proxy stands in for another object with the same interface to control access. A virtual proxy delays creating an expensive object until it is needed, a protection proxy checks permissions, a remote proxy hides network calls and a caching proxy stores results. Spring AOP and Hibernate lazy loading use proxies. A decorator adds behaviour and a proxy controls access, although the structure looks alike.

  10. 10

    Explain the Command pattern and where it is used.

    medium

    Command wraps a request as an object with an execute() method, and often undo(), so requests can be queued, logged, scheduled or reversed. A text editor stores each edit as a command on an undo stack. Job queues, macro recording and transactional scripts use it. It decouples the object that issues a request (the invoker) from the one that performs it (the receiver).

  11. 11

    Explain the State pattern with a vending machine or traffic light.

    hard

    State moves state-dependent behaviour out of large if-else blocks into one class per state. The context holds a current State and delegates calls; each state decides the transition. A vending machine has NoCoin, HasCoin and Dispensing states: insertCoin in NoCoin moves to HasCoin, while in HasCoin it refuses. Adding a SoldOut state means adding one class. Compared with Strategy, the states know about each other and change themselves, while strategies are chosen from outside.

  12. 12

    What is the Template Method pattern?

    medium

    A base class defines the skeleton of an algorithm in a final method, deferring certain steps to subclasses through abstract or overridable methods. A DataImporter has process() that calls read(), validate() and write(), and CSV and JSON importers implement the steps. It uses inheritance and the "Hollywood principle": do not call us, we will call you. Strategy achieves a similar goal through composition.

  13. 13

    Singleton, Prototype and Flyweight: what problem does each solve?

    medium

    Singleton ensures a single instance. Prototype creates new objects by cloning an existing one, useful when construction is costly or the exact class is unknown; copy depth matters. Flyweight shares common immutable state across many objects to save memory, for example sharing one glyph object per character in a document rather than one per occurrence. All three are about controlling object creation or storage, and Flyweight's shared part must be immutable.

  14. 14

    Which patterns would you use to design a notification system, and why?

    hard

    Strategy or a plain interface for channels (email, SMS, push), a Factory to build the right channel from configuration, Observer to trigger notifications when domain events occur, Template Method or Decorator to add retry and logging around any channel, and Builder to compose complex messages. Say which you would skip: Singleton is unnecessary if dependency injection supplies one instance. The reasoning, not the count of patterns, is what counts. A complete walk-through is in low-level design questions.

Frequently asked questions

How many design patterns are there?

The Gang of Four catalogue lists 23: five creational, seven structural and eleven behavioural. Many more exist in other catalogues.

Which design patterns should a fresher learn?

Singleton, Factory, Builder, Observer, Strategy and Decorator cover most interview questions, followed by Adapter and Facade.

Are patterns language specific?

No, but some are built into languages. Python functions and Java lambdas replace many Strategy and Command classes, and iterators are built in.

What is an anti-pattern?

A common solution that seems helpful but causes harm, such as the God Object or overused Singletons.

Related guides

More in CS Fundamentals Interview Questions

See all in this section