Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 57 ยท Practice and Interview Prep

Design Pattern and OOP Interview Questions

More than 40 design pattern, OOP and SOLID interview questions with concise answers, comparisons such as strategy vs state, and two runnable code demos.

Design interviews mix two kinds of questions. Some ask you to define and compare ideas: what is the difference between a decorator and a proxy? Others ask you to apply them: how would you design a notification system? This lesson covers the first kind with more than 40 questions and short answers, grouped by topic. For the second kind, practice with the projects and Low-Level Design Exercises with Solutions.

A good answer is short, correct and anchored in an example. The model answers below are deliberately compact: say the core idea in one or two sentences, add a concrete example if asked, and stop. Interviewers then ask follow-ups, and a crisp first answer gives you room to go deeper. Two of the trickiest comparisons come with runnable code, so you can see the difference instead of memorizing it.

How to answer

Define One sentence, in your own words.
Example A small real situation.
Trade-off When it helps and when it hurts.
1 / 2

Fundamentals

Q1. What is a design pattern? A named, reusable solution to a problem that keeps coming back in a particular context, with its trade-offs. It is a template for a design, not finished code. See What Are Design Patterns?.

Q2. What are the three categories of GoF patterns? Creational (how objects are created), structural (how objects and classes are composed) and behavioral (how objects communicate and share responsibility).

Q3. How is a pattern different from an algorithm? An algorithm is a precise sequence of steps that produces a result. A pattern describes the relationships between classes and the roles they play; the code for each role varies.

Q4. How is a pattern different from a framework or library? A library is code you call. A framework calls your code. A pattern is an idea you implement yourself, and it can appear inside both.

Q5. When should you not use a pattern? When no variation or change is expected, and a plain function or class does the job. Patterns add indirection. Adding one "just in case" is speculative generality.

Q6. Where do the 23 patterns come from? The book Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (the "Gang of Four", 1994) catalogued them. The authors named patterns that experienced designers already used.

Object-oriented fundamentals

Q7. What are the four pillars of OOP? Encapsulation (hide state behind methods), abstraction (expose what matters, hide how), inheritance (reuse and specialize), polymorphism (one interface, many behaviors). See OOP Foundations for Design.

Q8. Abstraction versus encapsulation? Abstraction decides what to show (a Car has drive()); encapsulation protects how it works (the engine's fields are private). One is about the design of the interface, the other about hiding the data behind it.

Q9. Interface versus abstract class? An interface declares a contract and, in most languages, holds no state. An abstract class can share fields and partial implementation, but a class can extend only one in Java and C#. Use an interface for a capability ("can be compared"), an abstract class for a family sharing code.

Q10. Why prefer composition over inheritance? Inheritance fixes the relationship at compile time and exposes the parent's internals to the child. Composition (holding another object and delegating) can change at run time, avoids deep hierarchies and keeps classes small. Inherit only for a true "is a" relationship.

Q11. Overloading versus overriding? Overloading is several methods with the same name and different parameters, resolved at compile time. Overriding replaces a parent method in a child with the same signature, resolved at run time. Only overriding is polymorphism.

Q12. Compile-time versus run-time polymorphism? Compile-time: overloading, templates, generics. Run-time: virtual dispatch, where the actual object's method is chosen when the call happens.

Q13. Coupling versus cohesion? Coupling is how much one module depends on another; you want it low. Cohesion is how closely the parts of a module belong together; you want it high. Good design has high cohesion inside and low coupling between.

Q14. Association, aggregation and composition? All are "has-a" links. Association: objects know each other. Aggregation: a whole holds parts that can live on their own (a team and its players). Composition: the parts die with the whole (an order and its lines). See Reading and Drawing UML.

SOLID and other principles

Q15. What is the Single Responsibility Principle? A class should have one reason to change. A report class that also formats and prints has three. See Single Responsibility Principle.

Q16. What is the Open/Closed Principle? Code should be open for extension and closed for modification: add new behavior by adding new classes, not by editing a growing if chain. Strategy and polymorphism are the usual tools. See Open/Closed Principle.

Q17. What is the Liskov Substitution Principle, with an example? A subtype must work wherever its base type is expected without breaking the caller's assumptions. The classic violation is a Square extending Rectangle: setting the width unexpectedly changes the height. See Liskov Substitution Principle.

Q18. What is the Interface Segregation Principle? Do not force clients to depend on methods they do not use. Prefer several small role interfaces to one fat one. A Printer should not have to implement fax(). See Interface Segregation Principle.

Q19. What is the Dependency Inversion Principle? High-level modules should not depend on low-level modules; both depend on abstractions. An OrderService depends on a PaymentGateway interface, not on a specific Stripe class. See Dependency Inversion and Dependency Injection.

Q20. Dependency inversion, inversion of control and dependency injection? DIP is a design principle about the direction of dependencies. IoC is the broader idea that a framework or container calls your code. DI is a technique: pass the dependencies in (constructor, setter) instead of creating them inside. A DI container automates the wiring.

Q21. What are DRY, KISS and YAGNI? DRY: do not repeat knowledge (not just text). KISS: choose the simplest design that works. YAGNI: do not build features before they are needed. They keep design honest. See DRY, KISS, YAGNI and More.

Q22. What is the Law of Demeter? An object should talk only to its direct collaborators, not to the collaborators' collaborators. order.customer.address.city chains couple you to the structure; ask the order instead (order.shippingCity()).

Creational patterns

Q23. What is Singleton and why is it criticized? It ensures one instance with a global access point. The criticisms: hidden global state, hard to test (you cannot substitute it), tight coupling, and extra care for threads. Prefer passing a single instance in. See Singleton.

Q24. How do you make a Singleton thread-safe? Create it eagerly at class-load time, use a holder class that the JVM initializes lazily, use an enum in Java, or lock around creation (double-checked locking with a volatile field). In JavaScript and Python a module-level object is already a singleton.

Q25. Factory Method versus Abstract Factory? Factory Method is one method (often overridden in a subclass) that creates one product. Abstract Factory is an object with several methods that create a whole family of related products that must match. See Factory Method and Abstract Factory.

Q26. What problem does Builder solve? Telescoping constructors with many optional parameters. A builder sets fields step by step, validates in build() and returns an immutable object. See Builder.

Q27. Shallow versus deep copy in Prototype? A shallow copy duplicates the object but shares nested objects with the original. A deep copy duplicates the whole graph. Prototype needs the deep one if the clone will be modified. See Prototype.

Q28. Static factory method versus a constructor? A static factory has a name (Color.fromHex), can return a cached or subtype instance, and can fail without creating an object. A constructor cannot do these things.

Q29. When is an object pool a mistake? When objects are cheap to create, because pooling adds complexity and risk of stale state. Pool only expensive resources such as connections. See Object Pool and Lazy Initialization.

Structural patterns

Q30. Adapter versus Facade? An adapter makes one existing interface fit the interface a client expects (one-to-one translation). A facade defines a new, simpler interface over a group of classes. See Adapter and Facade.

Q31. Decorator versus inheritance? Inheritance adds behavior at compile time and gives one subclass per combination. A decorator wraps an object at run time and stacks, so n features need n wrappers, not 2^n classes. See Decorator.

Q32. Decorator versus Proxy? Both wrap an object and share its interface. A decorator adds responsibilities chosen by the client. A proxy controls access (lazy loading, permissions, caching, remote call) and usually manages the real object's life cycle itself. See Proxy.

Q33. Bridge versus Adapter? Bridge is planned up front: it separates an abstraction from its implementations so both vary independently (shapes and renderers). Adapter is applied afterward to make incompatible existing classes work together. See Bridge.

Q34. What is Composite and where do you see it? It lets clients treat single objects and groups the same way through one interface. File systems (file and folder), UI trees and expression trees are examples. See Composite.

Q35. What does Flyweight save? Memory. It shares the immutable intrinsic state (a glyph's shape) among many objects and passes the extrinsic state (position) in from outside. See Flyweight.

Behavioral patterns

Q36. Strategy versus State? Both delegate to an interchangeable object. With Strategy, the client picks the algorithm and it usually stays put. With State, the object changes its own delegate as it moves through its life cycle, and states often know about each other. The code demo below shows the difference. See Strategy and State.

Q37. Observer versus publish-subscribe? In Observer, subjects know their observers directly. In publish-subscribe, a broker sits between publishers and subscribers, who do not know each other, and topics can filter messages. See Observer.

Q38. What is Command good for? Turning a request into an object, so you can queue it, log it, retry it and undo it. Undo stacks, job queues and macros use it. See Command.

Q39. Template Method versus Strategy? Template Method fixes the algorithm skeleton in a base class and lets subclasses fill in steps (inheritance, chosen at compile time). Strategy swaps the whole algorithm through composition at run time. See Template Method.

Q40. Why does Iterator exist? To traverse a collection without exposing how it is stored. Many languages built it in: for ... in, Java Iterable, Python __iter__, JavaScript generators. See Iterator.

Q41. What is Chain of Responsibility? A request passes along a chain of handlers until one handles it. Middleware, event bubbling and approval workflows use it. See Chain of Responsibility.

Q42. Mediator versus Observer? A mediator centralizes many-to-many communication: components talk only to the mediator, which decides who hears what (a chat room). Observer is one-to-many notification. Mediator can become a "god object" if it holds too much logic.

Q43. Memento in one sentence? An immutable snapshot of an object's state that lets you restore it later without breaking encapsulation. See Mediator and Memento.

Q44. What does Visitor add, and what does it cost? It adds new operations to a class hierarchy without changing the classes (double dispatch). The cost: adding a new element class forces changes in every visitor. See Visitor, Interpreter and Null Object.

Q45. What is the Null Object pattern? A do-nothing object with the same interface as a real one, used in place of null so callers need no null checks.

Practical and design-judgment questions

Q46. How do you decide which pattern to use? Start from the problem, not the pattern: what varies, what is likely to change, what is awkward today? Then match: swappable rules suggest Strategy, status-dependent behavior suggests State, creation by type suggests Factory, notification suggests Observer.

Q47. Which patterns become unnecessary in dynamic or functional languages? Many shrink to a function or a data structure: Strategy is a function parameter, Command is a closure, Iterator is a generator, Singleton is a module, Template Method is a higher-order function. See Patterns Across Languages.

Q48. Name some anti-patterns. God object, spaghetti code, singleton overuse, anemic domain model, golden hammer, speculative generality, primitive obsession. See Anti-Patterns and Code Smells.

Q49. How do you test code that uses a Singleton or global state? You cannot easily, which is the point of the criticism. Inject the dependency through the constructor or a parameter, and give tests a fake. If you inherit a singleton, add a reset hook for tests, and plan to remove it.

Q50. How do you make a design thread-safe? Prefer immutable data, confine mutable state to one thread or queue, make "check and update" atomic with a lock or compare-and-set, and keep critical sections small.

Two comparisons you can run

The pairs that interviewers love are the ones with the same shape and a different intent. The code below runs on the site, so you can see the difference.

Strategy versus State

In the first demo, the client chooses a strategy and the sorter never changes it. In the second, a traffic light replaces its own state after each tick. The structure is the same (a delegate); the control is different.

JS Strategy versus State

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Four wrappers: adapter, decorator, proxy, facade

All four put a layer in front of existing code. Compare what each layer is for.

JS Adapter, decorator, proxy and facade

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output with intent in mind. The adapter changed the interface; the decorator added behavior; the proxy controlled access; the facade simplified a group of parts.

Tips for the interview itself

  • Explain intent before structure. "Strategy lets the caller swap an algorithm" beats a recitation of class names.
  • Give a trade-off for every pattern. If you can only say good things about it, you do not understand it yet.
  • Use plain examples. Payments, notifications, shapes, files, coffee orders.
  • Admit uncertainty gracefully. Say what you know and reason from the principle.
  • Connect patterns to principles. Strategy and Decorator serve Open/Closed; DI serves Dependency Inversion.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between Strategy and State?

    Both delegate to a swappable object, but the control differs: the client drives Strategy, the object's own transitions drive State.
  2. 2. Which statement best separates Decorator from Proxy?

    Both keep the interface. Intent decides: adding behavior versus controlling access.
  3. 3. Why is Singleton often called an anti-pattern?

    The problem is the global access point, which hides dependencies and blocks substitution in tests.
  4. 4. A Square extends Rectangle, and code that sets the width of a Rectangle now sees the height change too. Which principle is broken?

    A subtype must keep the behavior callers expect from the base type. The square changes the meaning of setWidth.
  5. 5. What is the best first step when asked 'which pattern would you use here?'

    Patterns answer problems. Start from the problem and the expected change, not from the pattern list.

Summary

  • Know the intent of each pattern first; most wrong answers come from confusing look-alike patterns.
  • The pairs to master are Strategy versus State, Adapter versus Facade, Decorator versus Proxy, Factory Method versus Abstract Factory, Template Method versus Strategy, and Observer versus Mediator.
  • Tie patterns to principles: Open/Closed, Dependency Inversion and composition over inheritance explain why most patterns exist.
  • Singleton, deep inheritance and speculative abstraction are the usual targets of "what could go wrong" questions.
  • In dynamic and functional languages many patterns reduce to functions, closures, modules and generators.
  • Answer in three beats: definition, example, trade-off.

Next lesson: Design Patterns Cheat Sheet.