61 Design Patterns interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
Design patterns are named, reusable solutions to recurring problems in structuring object-oriented code, usually studied alongside the SOLID principles. This section groups questions into creational, structural and behavioral patterns, including Strategy, Builder, Factory, Singleton, Observer, Decorator and Adapter, plus OOP fundamentals and refactoring scenarios drawn from everyday code.
and 12 more topics.
SRP states that each class or module should have only one reason to change — responsible for only a single piece of functionality. TypeScript example: Those three methods belong to three different concerns: login rules, logging infrastructure, and email. Keeping them in one class means…
OCP states that a module should be open for extension but closed for modification — add new features without changing existing code. TypeScript example: In the first version, every new marketing promotion means opening calculatePriceOld and editing it, which can break branches that already work.…
LSP states that objects of a subclass must be substitutable for objects of the superclass without breaking program correctness. The classic violation: Square extends Rectangle and overrides both setWidth/setHeight to keep the sides equal. resize only knows it has a Rectangle, so it expects changing…
Interface Segregation Principle (ISP): a class should not be forced to implement methods it does not use. Instead of one large interface, split it into several small ones, each wrapping one group of behavior. Fish is forced to implement fly() and run() even though it…
DIP has two rules: (1) high-level modules should not depend on low-level modules — both should depend on abstractions; (2) abstractions should not depend on details — details should depend on abstractions. For example, UserService should not new MySQLDatabase() directly but instead receive a DatabaseInterface…
DRY (Don't Repeat Yourself): each business rule is written in one place. KISS (Keep It Simple, Stupid): choose the simplest approach that still solves the problem. YAGNI (You Aren't Gonna Need It): if a feature is not needed yet, do not write it yet. In…
SOLID helps produce maintainable, extensible, and testable code — the three factors that determine a software project's longevity. As a team scales, SOLID enables multiple developers to work in parallel on the same codebase with fewer conflicts because module boundaries are clearly defined. SOLID also…
In React, SOLID applies not to classes but to components, custom hooks and API modules. The three principles used most are SRP, OCP and DIP. - SRP (one reason to change): useUser fetches data, UserCard renders it. An API change touches the hook, a UI…
Singleton ensures a class has exactly one instance, reached through a single access point, getInstance(). The constructor is private, so outside code cannot call new itself. In Node.js you usually do not need a class like that: a module is loaded once and cached, so…
Factory Method defines an interface for creating an object but lets subclasses decide which class to instantiate — the parent class doesn't hard-code a specific concrete class. TypeScript example: Difference from Simple Factory: - Simple Factory (not a GoF pattern) is just a method or…
Abstract Factory is an interface that creates a whole group of related objects without making the caller know the concrete classes. Each implementation of the interface returns a complete set, so objects taken from the same factory always match. WindowsUIFactory only creates WindowsButton and WindowsCheckbox,…
Builder separates the construction of a complex object into discrete steps, enabling different representations of the same object. TypeScript example with method chaining: Advantages over many-parameter constructors: - No need to remember parameter order: each value comes with a method name, so 10 is clearly…
Prototype is a pattern that creates new objects by cloning an existing object instead of building them again through a constructor. The original acts as a template; the clone changes a few fields and is ready to use. clone() copies filters as well, so editing…
Object Pool keeps a set of pre-initialized objects around for reuse instead of constantly creating and destroying them — worth it when construction is expensive. The most common case is a database connection pool: rather than opening a connection per request, the pool holds N…
DI is the technique where an object receives its dependencies from the outside rather than creating them — it is the mechanism that implements DIP. Three types of DI: DI frameworks: NestJS uses an IoC container with @Injectable() and @Inject() decorators that automatically resolve the…
Creational patterns are the patterns that handle creating objects, so the code that uses an object is not tied to new ConcreteClass(...). You only need them when object creation starts to hurt: a constructor with too many parameters, choosing a class based on configuration, or…
Adapter allows incompatible interfaces to work together by wrapping an object in a wrapper that exposes the interface the client expects. Real-world example: integrating a third-party payment SDK: Your code only calls charge(cents); the adapter converts to the unit and method name the SDK expects.…
Bridge splits one concept into two independent parts: the abstraction (the object the client works with) and the implementation (the concrete way the work gets done underneath). The abstraction holds a reference to the implementation instead of inheriting from it, so each side can add…
Composite is for tree-shaped data, where a group can contain both single items and other groups. The single item (leaf) and the group (composite) implement the same interface, so the client calls the same method on both without checking which one it holds. root holds…
Decorator adds behavior to an object by wrapping it in another object with the same interface. The wrapper does its own work and then calls the inner object, so you can stack several layers and pick the combination at runtime. Calling myCoffee.cost() makes SugarDecorator ask…
Facade is a layer that sits in front of a group of complex modules (a subsystem) and offers a few simpler functions to the client. The client calls one facade function, and the facade calls the underlying modules in the right order. The component only…
A Proxy is an object that stands in for the real object (the subject) and has the same interface. The client calls the proxy exactly as it would call the real object, and the proxy decides whether to forward the call and what to do…
Flyweight is a pattern that saves memory when you have huge numbers of similar objects: the shared data (intrinsic state) is created once and shared, while each object keeps only its own part (extrinsic state). The classic example is a game drawing 10,000 trees in…
Structural patterns are the patterns that deal with putting classes and objects together: wrapping an object, connecting two interfaces, or grouping many objects into one unit. Most of them share the same technique, one object holding a reference to another and forwarding calls to it.…
Observer has a subject that holds data and a list of observers (functions or objects that want to know when the data changes). Observers register themselves with the subject. When the data changes, the subject calls each observer in the list, so it does not…
Strategy pulls each way of doing the same job (an algorithm) into its own object behind a shared interface. The code that uses it only holds a strategy and calls it, so to change the behavior you pass in a different strategy, even at runtime.…
Command is a pattern that wraps an operation in an object with execute() to run it and usually undo() to reverse it. Because the operation is now data, you can store it in a list, queue it, log it or replay it. Undo/Redo relies on…
Template Method is a pattern where the parent class has one method that fixes the order of the steps of an algorithm, and subclasses override only specific steps. Strategy instead pulls the whole algorithm out into a separate object that is passed in at runtime.…
Chain of Responsibility arranges handlers into a chain and passes a request through them in order. Each handler decides: handle it and stop, or pass it to the next one. The sender only knows the head of the chain, not who ends up handling the…
The State pattern lets an object change behavior when its internal state changes; from the outside it looks like the object changed class. Instead of scattering if (state === 'idle') ... else if (state === 'loading') ... through the codebase, each state is a class…
Iterator is a pattern that lets you walk through a collection's elements one by one without knowing whether it is stored as an array, a tree or fetched from an API. JavaScript builds this pattern in through two protocols: - Iterator: an object with a…
All three split UI into a Model (data and business rules), a View (what is displayed) and a layer in between. They differ in who that middle layer is and how the View gets updated. MVC MVP MVVM ------------ Middle layer Controller Presenter ViewModel Who…
- Encapsulation: bundle data and the behavior operating on it into one object and hide internal state; the outside touches it only through a public interface. This protects invariants and reduces coupling. - Abstraction: expose "what" an object does and hide "how". Think of a…
Idea: capture and store an object's internal state so it can be restored later, without breaking encapsulation (its internals are never exposed outside). Three roles: - Originator: the object whose state must be saved; it creates a memento (save()) and restores from one (restore(m)). -…
Problem: scattered if (obj != null) obj.doSomething() is noisy, easy to forget, and leads to NullPointerExceptions. Idea: instead of returning null for "nothing", return an object that implements the same interface but with neutral / do-nothing behavior. Example: interface Logger { log(msg) }. Rather than…
Three levels of object relationship, with increasingly strong lifecycle coupling: - Association: two objects are related and use each other but have independent lifecycles. E.g. Teacher and Student — they know each other but exist separately. UML: a plain line. - Aggregation (loose "has-a"): a…
- Cohesion: how strongly the parts inside a module serve one clear purpose. High cohesion = every function/field in the module relates tightly to a single responsibility (close to SRP). - Coupling: how much a module depends on the internals of another. Low coupling =…
This is the classic switch statements smell: one function branching on a type, edited every time a new type appears. The fix is to extract each branch into a strategy behind one interface, then pick the strategy from a lookup table. A new carrier is…
That is the telescoping constructor problem — nobody can tell what true in position six means, and swapping two same-typed arguments compiles fine. Two options: 1. A parameter object (enough for most TS/JS code): Field names carry the meaning, and optional values are simply omitted…
Factory Method is when a parent class calls a creation method and a subclass decides which concrete class to create. Abstract Factory is an interface with several creation methods, each for one object in a group that must match each other; each implementation returns a…
Having exactly one instance is not the problem — the problem is that the classic Singleton owns its own instance and is called directly from everywhere. Consequences: - Hidden dependencies. OrderService calls Database.getInstance() internally, so its signature never reveals that it needs a database. Reading…
The problem is that markPaid knows too much about everything around it: each new post-payment task means editing it again. Split it with Observer / publish-subscribe — markPaid updates state and emits an event, and interested parties subscribe themselves. New behavior is a new subscriber,…
Use a Decorator: wrap the original object in another object with the same interface, add behavior before or after, and delegate the real work inward. Each requirement (cache, retry, timing) is its own wrapper layer. One api.get(sku) call goes from the outside in: TimedPriceApi starts…
Define an interface in your own domain vocabulary, then write an Adapter that translates it to the SDK. Business code only sees PaymentGateway. Switching providers means writing a new adapter; nothing else changes. Tests get easier too, since the adapter can be replaced by a…
Yes — with a Facade (one entry point for one process), not a catch-all "Manager" class. The controller shrinks to: validate request → call register → map response. The signup process lives in one place and can be tested without HTTP. Boundaries to keep: -…
Repository puts a layer between the domain and storage: the domain works with what looks like an in-memory collection, while SQL/ORM details sit behind the interface. What it buys you: - Business queries get names and are reusable, instead of every service assembling its own…
Both separate creating a dependency from using it, but the direction differs. DI — dependencies are handed in from outside: Service Locator — the class fetches them from a registry: Why DI wins: - Dependencies are visible in the signature. The constructor tells you what…
Template Method fits better when the skeleton is fixed and only a few steps vary. The base class owns the sequence; subclasses fill in the differences. Strategy fits better when the varying part is a standalone behavior chosen at runtime or reused in other contexts:…
A Decorator adds behaviour to an object; a Proxy controls access to an object. The structure is almost identical; they differ in purpose and in who decides to do the wrapping. Decorator Proxy --------- Purpose Add features: logging, compression, retry, formatting Control access: lazy loading,…
OOP fits when the problem has many "entities" with their own state and behaviour tied to that state, such as orders, accounts, game characters, UI widgets. Encapsulation lets each object enforce its own rules (a delivered order cannot be cancelled), and polymorphism lets you add…
Start from use cases, not classes. Clarify scope with the interviewer: members borrow and return books, a borrowing limit, late fees, reserving a book someone else holds. From those sentences, nouns become classes and verbs become methods. The main classes, plus one point interviewers often…
Pin down requirements first: the lot has several levels, each spot fits one vehicle size (motorbike, car, truck); on entry a ticket is issued and a suitable free spot assigned; on exit the fee is calculated by duration. In an assignment, the main thing graded…