Design patterns interview questions with code and when to use each

Design patterns interview questions check whether you know the common Gang of Four patterns well enough to pick one for a real problem, write it in a few lines, and say when it would be overkill. Fundamentals rounds ask for definitions and the three categories (creational, structural, behavioral), intermediate rounds ask you to compare look-alike patterns such as decorator and proxy, and senior rounds hide a pattern inside a design problem like undo, plugins or notifications. Lead with the problem the pattern solves, then the structure, then the cost.

By Published 9 min read

Where design pattern questions come up

Pattern questions appear in three places. Object-oriented fundamentals rounds for Java, C#, C++ and Python roles ask you to define and sketch a handful of patterns. Low-level design rounds give you a small system (a parking lot, a vending machine, a logger, a notification service) and watch which structures you reach for. Code review style questions show you a long if-else chain or a tangled class and ask how you would restructure it. In every format, interviewers listen for the reason behind a pattern, since naming one without a problem to solve is a common way to lose points.

The examples below use JavaScript and Python because both run anywhere and keep the structure visible. In Java or C# you would add explicit interfaces, but the ideas carry over unchanged.

Fundamentals

Fundamentals questions about patterns in general
QuestionWhat it testsWhat a strong answer shows
What is a design pattern?DefinitionA named, reusable solution to a problem that keeps recurring in software design, described as intent, structure and consequences. It is a template for thinking, not a library you import.
What are the three Gang of Four categories?CatalogCreational patterns control how objects are made (factory method, abstract factory, builder, prototype, singleton). Structural patterns compose objects into larger shapes (adapter, bridge, composite, decorator, facade, flyweight, proxy). Behavioral patterns divide responsibility and communication (strategy, observer, command, state, template method, iterator, chain of responsibility and others).
Pattern, algorithm and architectural style: what is the difference?VocabularyAn algorithm solves a computational problem step by step. A design pattern arranges classes and objects to manage change. An architectural style such as layered, microservices or event-driven shapes a whole system.
Why favor composition over inheritance when applying patterns?Design senseMost GoF patterns plug objects together at run time. Composition lets you swap behavior without growing a class hierarchy and avoids subclasses that depend on a parent's internals.
Can using patterns make code worse?JudgmentYes. Extra indirection costs readability, and a pattern applied for a variation that never comes is pure overhead. Add the structure when the second or third variant appears.
Which patterns do you use most, and where?ExperienceA specific answer with real places: strategy for pricing rules, adapter around a payment vendor's SDK, observer for domain events. Generic lists sound memorized.
How do patterns change in languages with first-class functions?Language fluencySeveral behavioral patterns shrink to a function or a closure. Strategy becomes a function argument, command becomes a callable, and iterator is built into the language as generators or the iterable protocol.
Fundamentals questions about patterns in general. Scroll sideways on a small screen.

Creational pattern questions

  • Factory method versus abstract factory? A factory method is one overridable method that decides which concrete class to create. An abstract factory is an object that creates a whole family of related products, such as a set of UI widgets for one platform, so they always match.
  • When is a builder worth it? When an object has many optional parts or must be assembled in steps and validated before use, such as an HTTP request or a query. It replaces long constructors where nobody remembers the argument order.
  • Why do many teams avoid singletons? A singleton is global state with a nicer name. It hides dependencies, leaks state between tests, and needs care with threads. Creating one instance at startup and passing it in gives the same single instance without those costs.
  • How do you write a thread-safe lazy singleton in Java if you must? The holder-class idiom or an enum singleton is simplest. Double-checked locking also works when the field is volatile, but it is easy to get wrong and hard to read.
  • What problem does the prototype pattern solve? Creating new objects by copying a configured instance, which helps when setup is expensive or the exact class is only known at run time. Be ready to discuss shallow versus deep copies.
  • How is dependency injection related to the creational patterns? It moves the creation decision out of the class that uses an object into a composition root or container. Factories still appear, but behind the injection point.

Structural pattern questions

Structural patterns and the comparisons interviewers like
QuestionWhat it testsWhat a strong answer shows
Adapter versus facade?Look-alikesAn adapter converts one existing interface into the one your code expects, typically around a third-party SDK. A facade offers a new, simpler interface over a complicated subsystem. One translates, the other simplifies.
Decorator versus proxy?Look-alikesBoth wrap an object with the same interface. A decorator adds behavior and is meant to be stacked. A proxy controls access to the real object: lazy loading, permission checks, remote calls or caching, usually as a single layer.
When would you use the composite pattern?TreesWhen clients should treat a single item and a group of items the same way: files and folders, UI components containing components, or an order line versus a bundle of lines.
What does the bridge pattern separate?Two dimensionsAn abstraction from its implementation, so both can vary independently. Shapes and renderers, or notifications and delivery channels, avoid a subclass for every combination.
What is the flyweight pattern for?MemorySharing the common, unchanging state of many similar objects, such as glyphs in a text editor or tiles in a game, while each use keeps only its own small state.
Where does the decorator pattern show up in practice?RecognitionJava I/O streams wrap one another, middleware wraps a handler, and caching or logging layers wrap a repository. Python's @decorator syntax wraps functions and is related but not identical.
Structural patterns and the comparisons interviewers like. Scroll sideways on a small screen.
from abc import ABC, abstractmethod


class Repository(ABC):
    @abstractmethod
    def get(self, key): ...


class DbRepository(Repository):
    def __init__(self):
        self.calls = 0

    def get(self, key):
        self.calls += 1                    # pretend this is a slow query
        return {"id": key, "name": "user" + str(key)}


class CachingRepository(Repository):
    """Decorator: same interface, adds caching around any repository."""

    def __init__(self, inner):
        self.inner, self.cache = inner, {}

    def get(self, key):
        if key not in self.cache:
            self.cache[key] = self.inner.get(key)
        return self.cache[key]


class LoggingRepository(Repository):
    def __init__(self, inner):
        self.inner = inner

    def get(self, key):
        print("get", key)
        return self.inner.get(key)


db = DbRepository()
repo = LoggingRepository(CachingRepository(db))   # wrappers stack in any order
repo.get(7)
repo.get(7)
print("database calls:", db.calls)               # get 7, get 7, database calls: 1
Decorator pattern: caching and logging wrap any repository without changing it, and the wrappers stack in any order.

Behavioral pattern questions

  • Strategy versus state? Both swap an object's behavior behind one interface. With strategy, the caller picks the behavior and it rarely changes during the object's life. With state, the object moves itself between states, and each state decides the next one, as in an order going from placed to paid to shipped.
  • What problem does the observer pattern solve, and what are its risks? It lets a subject notify any number of listeners without knowing who they are. Risks are forgotten subscriptions that keep objects alive, surprising update order, and cascades where one event triggers many others.
  • How does the command pattern enable undo? Each action becomes an object with execute and undo. Executed commands go onto a history stack, so undo pops one and reverses it. Commands can also be queued, logged or retried.
  • Template method versus strategy? Template method fixes the steps of an algorithm in a base class and lets subclasses fill some in, using inheritance. Strategy passes the varying part in as an object or function, using composition, which is easier to test.
  • Where have you seen chain of responsibility? Web middleware, logging handler chains and approval workflows. Each link either handles the request or passes it on, so you can add or reorder steps without touching the others.
  • What does the iterator pattern give you? A way to walk a collection without exposing its internals. Most languages build it in, so the interview point is often writing a custom iterable or generator.
  • When is the visitor pattern useful, and why is it unpopular? It adds operations over a fixed set of node types, as compilers do over syntax trees. Adding a new node type means touching every visitor, so it fits only stable hierarchies.
  • What is the mediator pattern? A central object that coordinates components so they stop referring to each other directly, such as a dialog that wires its fields together. It reduces many-to-many links but can grow into a god object.
const strategies = {
  none: (total) => total,
  percent: (total, pct) => total * (1 - pct / 100),
  bulk: (total, minItems, items) => (items >= minItems ? total * 0.9 : total),
};

class Checkout {
  constructor(strategyName, ...args) {
    const rule = strategies[strategyName];
    if (!rule) throw new Error("unknown strategy: " + strategyName);
    this.apply = (total, items) => rule(total, ...args, items);
  }
}

console.log(new Checkout("none").apply(200, 3));          // 200
console.log(new Checkout("percent", 15).apply(200, 3));   // 170
console.log(new Checkout("bulk", 5).apply(200, 6));       // 180
Strategy in JavaScript: each discount rule is a plain function behind one call shape, chosen by name at run time. No class hierarchy needed.
class EventBus {
  constructor() { this.handlers = new Map(); }
  subscribe(topic, fn) {
    if (!this.handlers.has(topic)) this.handlers.set(topic, new Set());
    this.handlers.get(topic).add(fn);
    return () => this.handlers.get(topic).delete(fn);
  }
  publish(topic, payload) {
    for (const fn of this.handlers.get(topic) || []) fn(payload);
  }
}

const bus = new EventBus();
const stop = bus.subscribe("price", (p) => console.log("email sees", p));
bus.subscribe("price", (p) => console.log("cache sees", p));
bus.publish("price", 42);   // email sees 42, cache sees 42
stop();
bus.publish("price", 43);   // cache sees 43 only
Observer with a built-in way out: subscribe returns its own unsubscribe function, which is the usual answer to the leak follow-up.
class Handler:
    def __init__(self, successor=None):
        self.successor = successor

    def handle(self, amount):
        if self.successor:
            return self.successor.handle(amount)
        return "rejected"


class TeamLead(Handler):
    def handle(self, amount):
        return "team lead approves" if amount <= 1000 else super().handle(amount)


class Director(Handler):
    def handle(self, amount):
        return "director approves" if amount <= 10000 else super().handle(amount)


chain = TeamLead(Director())
for amount in (500, 5000, 50000):
    print(amount, chain.handle(amount))
# 500 team lead approves / 5000 director approves / 50000 rejected
Chain of responsibility for an expense approval: each approver handles what it can and passes the rest along.

Senior and scenario questions

Pattern questions dressed up as design problems
QuestionWhat it testsWhat a strong answer shows
Design undo and redo for a drawing app.Command and mementoCommands with execute and undo on two stacks; clear redo on any new action. For actions that are hard to reverse, store a memento (snapshot) of the affected state instead. Mention memory limits on history.
Design a plugin system for an editor.ExtensibilityA small stable interface plugins implement, a registry that discovers them, events (observer) for hooks, and an adapter layer so internal changes do not break plugins. Sandboxing and versioning come up next.
This function has a 200-line switch on payment type. Refactor it.RefactoringMove each branch behind a common interface (strategy), pick the implementation from a map or factory, and add tests around the old behavior before moving anything.
Which patterns does your web framework use?RecognitionMiddleware is a chain of responsibility, route handlers are commands, ORMs use active record or data mapper and unit of work, dependency injection containers act as factories, and event emitters are observers.
Name anti-patterns you have seen and fixed.ExperienceGod objects, singletons used as global variables, deep inheritance trees, a service locator hiding every dependency, and patterns added for flexibility nobody needed. Explain the fix, not only the label.
How do patterns relate to distributed systems patterns such as retry, circuit breaker or saga?BreadthSame idea at a different scale: named solutions to recurring problems. Circuit breaker resembles a proxy with state; saga coordinates steps with compensating actions, similar to commands with undo.
When would you skip a pattern you know fits?RestraintWhen there is one implementation and no sign of a second, when the team does not know it and the gain is small, or when the language already provides it. Readable code wins over textbook structure.
Pattern questions dressed up as design problems. Scroll sideways on a small screen.

Fictional example

Answering "Design notifications that can go by email, SMS or chat, with quiet hours"
Interviewer
Users pick channels, and some want no messages at night. Which patterns would you use, and where?
Candidate
I would keep it small. Each channel is a sender with one method, send, so email, SMS and chat are interchangeable strategies chosen from a map keyed by the user's preference. If one channel's SDK has an awkward interface, I wrap it in an adapter so it matches. Quiet hours and retries are cross-cutting, so I would put them in decorators around any sender: a quiet-hours wrapper that defers the message, and a retry wrapper with backoff. Business events such as an order shipping are published on an event bus, and the notification service subscribes, so the order code does not know notifications exist. I would not add an abstract factory here, since we only have one family of senders. The first thing I would test is the quiet-hours wrapper with a fake clock.

A ten-day design patterns practice plan

  1. Days 1 and 2: the core tenStrategy, observer, decorator, adapter, facade, factory method, builder, command, state and composite. For each, write the problem in one sentence before any code.
  2. Days 3 and 4: the look-alike pairsWrite a two-line difference for each pair: decorator and proxy, strategy and state, adapter and facade, factory method and abstract factory, template method and strategy.
  3. Days 5 and 6: code them smallImplement each core pattern in your interview language in under 40 lines, then again with plain functions where the language allows, and compare.
  4. Days 7 and 8: find them in real codeOpen a framework you use and locate three patterns. Being able to say where you saw one in production is worth more than a textbook definition.
  5. Days 9 and 10: design roundsPractice two low-level design problems aloud with a timer, naming each pattern only when it earns its place and stating what you left out.

Patterns rest on principles, so pair this page with SOLID principles interview questions, and revise the basics on OOP interview questions. Front-end candidates will find the plugin and loader architecture of bundlers on the webpack interview questions page, and larger structures on the system design hub.

A useful drill is explaining a pattern aloud and hearing whether you led with the problem or with the diagram. Natively, an AI interview assistant on Mac and Windows, keeps a transcript of each mock design round, suggests answers live if you blank on the difference between two look-alike patterns, and reads a refactoring prompt or class diagram from a screenshot so you can check its structure against yours. When you add your résumé and a job description, on Pro or the free trial, it frames suggestions around the stack you actually work in.

Questions people ask

What design patterns are asked about most in interviews?

Strategy, observer, decorator, adapter, facade, factory method, builder, singleton, command and state come up most often, usually with a request to compare two similar ones or apply one to a small design problem.

What are the three types of design patterns?

Creational patterns control object creation, structural patterns compose objects into larger structures, and behavioral patterns assign responsibilities and manage how objects communicate.

What is the difference between the decorator and proxy patterns?

Both wrap an object behind the same interface. A decorator adds behavior and is meant to be stacked; a proxy controls access to the real object, for example by loading it lazily, checking permissions or calling it remotely.

Do I need to memorize all 23 Gang of Four patterns?

No. Know about ten well enough to explain the problem each solves, write a short version and name its downside, and be able to recognize the rest by name and intent.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP