Top 20 Design Patterns Interview Questions

An important subject in object-oriented design interviews is design patterns. In addition to understanding what each pattern is, interviewers want to know why you use it, when it’s right (and when it isn’t), how it relates to design principles (like SOLID), and how you would use it in real-life scenarios. 20 commonly asked questions are listed in the sections below, each with a suggested approach and sample answer.

Interview Questions

What is a Design Pattern?

Suggested approach: Give a brief explanation first, then go into more detail about the importance of these templates in software design.

Sample answer:

A design pattern is a reusable approach to a design issue that comes up often in software development. It is a template or blueprint that you can change to fit a specific scenario rather than a complete design that can be immediately converted into code. The Observer pattern, for example, is a tried-and-true method of organizing interactions when multiple components of a system must inform one another of changes.

Design patterns are important because they aid code reuse, optimize maintainability, offer teams a common language, and simplify the reasoning behind complex systems.

How are Design Patterns different from Algorithms?

Suggested approach: Examine and compare the two, paying specific attention to the level of abstraction and the purpose.

Sample answer:

Algorithms are methodical processes used to respond to specific computational issues (for example, sorting an array). In comparison, design patterns deal with structural and architectural issues, such as how classes and objects interact, how duties are assigned, and how flexibility is maintained. A design pattern explains to you how to arrange your system so that modifications are simpler to implement, whereas an algorithm might tell you how to sort.

What are the major Categories of Design Patterns?

Suggested approach: List each category and offer a brief explanation.

Sample answer:

Typically, design patterns fall into one of three major categories:
  • Creational patterns, which include mechanisms for creating objects (e.g., Singleton, Factory Method, Builder).
  • Structural patterns, such as adapter, bridge, composite, and decorator, focus on object composition and relationships between classes and objects.
  • Behavioral patterns (such as Strategy, Observer, Command, and Iterator) that deal with communication and object interaction.

Depending on the language and domain, some sources also include additional categories (such as concurrency or architectural patterns).

What are the Advantages of Using Design Patterns?

Suggested approach: Highlight and describe the main benefits.

Sample answer:
  • Tested fixes: Patterns reduce the risk of reinventing the wheel by capturing best practices that have been tried and tested over time.
  • Reusability: They encourage the use of design concepts in different system components and even in different projects.
  • Better communication: Team members can discuss and review designs more easily when they have names such as “Observer” or “Factory.”
  • Improved architecture: Patterns aid evolution, increase cohesion, decrease coupling, and organize responsibilities.
  • Clarity and maintainability: Well-chosen patterns aid easier code evolution and understanding.

When shouldn’t you use a Design Pattern?

Suggested approach: Demonstrate your awareness that patterns can be exploited and are not a silver bullet.

Sample answer:

Design patterns are not magic fixes; they are tools. They should not be utilized in the following situations:
  • The problem is simple, and introducing a pattern would add needless complexity.
  • The pattern over-engineers the design, making it more difficult to understand.
  • The pattern’s flexibility is not needed by the team or system (for example, if one implementation will actually never change).

Using a pattern hinders appropriate unit testing or injects global state when it is not needed (e.g., a misused Singleton). Just as vital as knowing when to apply a pattern is understanding when not to.

Explain the Singleton Pattern and when to use it.

Suggested approach: Describe, clarify important players or roles, provide a use case, and talk about trade-offs.

Sample answer:
  • Definition: A class is assured to have a single instance due to the Singleton pattern, which also provides a global point of access to that instance.
  • Use case: Useful when coordinating resource needs for a single object (e.g., a connection pool manager, logging subsystem, or configuration manager).
  • Trade-offs: Global state, hidden dependencies, unit testing challenges, and concurrency problems (if the Singleton isn’t thread-safe) can be caused by excessive use, despite its usefulness.

Dependency Injection is sometimes a better option.

Explain the Factory Method vs Abstract Factory pattern.

Suggested approach: Define each, point out the differences, and list the use cases.

Sample answer:
  • Factory method: A creational pattern that enables subclasses to select which class to instantiate while defining an interface for doing so. This allows a class to let subclasses handle instantiation.
  • Abstract Factory: A pattern that provides an interface for building families of related or dependent objects without defining their specific classes. It includes a collection of unique factories.
  • Difference: Abstract Factory creates a family of related objects without defining their specific classes, whereas Factory Method assigns object creation to subclasses.
  • Use-case: If you need to select which subclass to create at runtime, use the Factory Method. If your system needs to create several related objects that belong together and you want to change their families with ease, use the Abstract Factory.

What is the Builder Pattern, and how does it differ from Factory?

Suggested approach: Define, list the steps, and compare to the factory.

Sample answer:
  • Definition: The Builder pattern allows for the creation of multiple representations using the same construction process by separating the construction of a complex object from its representation.
  • Use-case: When you want to build an object step-by-step, or when it has a lot of parts or optional parameters.
  • Difference from Factory: Factory patterns focus on creating objects of different types (which subtype to instantiate). Builder offers control over the construction process and is geared towards building a complex object piece by piece (especially useful where there are multiple optional parameters or combinations).

For example, a VehicleFactory generates a car or truck based on a parameter, while a MealBuilder assembles a multi-course meal.

What is the Adapter Pattern?

Suggested approach: Define, give a specific example, and point out its applications.

Sample answer:
  • Definition: By constructing a wrapper (adapter) that converts one interface into another expected one, the adapter pattern allows incompatible interfaces to cooperate.
  • Use-case: When you wish to reuse an existing class without changing its interface because it does not meet your client’s expectations.
  • Example: Consider you have a LegacyPrinter class with printData(), and your client expects print(), you wrap LegacyPrinter with an AdapterPrinter that conforms to the new interface.
  • Benefits: Interoperability, interface and implementation decoupling, and the capability to reuse existing code.

What is the Bridge Pattern, and how is it different from Adapter?

Suggested approach: Define Bridge, compare it with Adapter, and use cases.

Sample answer:
  • Definition: An abstraction and its implementation are separated by the Bridge pattern, enabling independent variation between the two. To put it another way, you segregate the implementation of the interface (abstraction) into unique class hierarchies.
  • Difference with the adapter: Making two existing interfaces work together (usually one-off) is the goal of an adapter. Creating a system from the ground up enables abstraction and implementation to develop separately. A bridge is a planned structural separation, whereas an adapter is a structural retrofit.
  • Use-case: Imagine you have multiple iterations of DeviceImplementation (TV, Radio) and RemoteControl (abstraction). With Bridge, you can mix and match a remote control with a range of device implementations without worrying about subclass explosion.

What is the Decorator Pattern?

Suggested approach: Describe, show diagrams, and explain the benefits in prose.

Sample answer:
  • Definition: An object can dynamically need new responsibilities using the Decorator pattern without changing its structure, that is, without subclassing. It offers a versatile substitute for subclassing when it comes to adding functionality.
  • Use-case: Imagine you wish to add decoration to a TextView class, like scrollbars, borders, shadows, etc. You create decorator classes like BorderDecorator. ScrollbarDecorator, etc., rather than subclasses like BorderedTextView and ScrollableTextView.
  • Benefits: Prevents subclass explosion, allows decorator combinations at runtime, and promotes the open/closed principle (extending behavior without changing the original class).

What is the Composite Pattern?

Suggested approach: Describe the part-whole hierarchy, its context, and when to apply it.

Sample answer:
  • Definition: To describe “part-whole” hierarchies, the Composite pattern groups objects into tree structures. It allows clients to handle both individual objects and object compositions consistently.
  • Use-case: Consider that in addition to GUI elements like TextField and Button, you also have Panels that can have children (textfields, buttons, or other panels). You can treat a Panel and a Button consistently by utilizing Composite (both implement the UIComponent interface).
  • Benefits: Supports dynamic tree changes, simplifies client code by treating leaves and composites equally, and simplifies recursive structures.

What is the Flyweight Pattern?

Suggested approach: Define and explain the use case of memory and the difference between intrinsic and extrinsic states.

Sample answer:
  • Definition: By externalizing the different parts (extrinsic state) and sharing the common parts (intrinsic state), the Flyweight pattern reduces the memory cost of many similar objects.
  • Use-case: Every character in a text editor could be an object. A flyweight object stores glyph data once, and each character object references it, storing only position or color (extrinsic) rather than font metrics and glyph data for every character.
  • Benefits: Memory savings, sharing, and compatibility with systems that have a lot of fine-grained objects with only a few different properties.

Explain the Strategy Pattern.

Suggested approach: Explain, discuss the interface, and provide examples of different algorithms.

Sample answer:
  • Definition: A family of algorithms is defined, encapsulated, and rendered interchangeable by the Strategy pattern. At runtime, the client chooses the algorithm.
  • Use-case: Consider you have a payment system, you might wish to use PayPal, CreditCard, ApplePay, etc. For each, you specify a PaymentStrategy interface and specific tactics. You select which one to use at runtime.
  • Benefits: Encouraging the Open/Closed principle, removing conditional logic (switch/case) from client code, and allowing behavior extension without client modification.

Explain the Observer Pattern.

Suggested approach: Describe the “subject/observer” relationship and how event systems use it.

Sample answer:
  • Definition: The Observer pattern establishes a one-to-many dependency between objects, allowing all of its dependents (observers) to be automatically updated and notified when one object (the subject) changes state.
  • Use-case: Multiple views in user interfaces can automatically update and subscribe when a data model changes. Alternatively, in a stock-market system, all registered consoles or graphs are updated in response to changes in stock prices.
  • Benefits: Dynamic registration and unregistration, loose coupling between subjects and observers, and compatibility with event-driven architectures.

What is the Command Pattern?

Suggested approach: Define the request as an object and display use cases such as queueing and undo/redo.

Sample answer:
  • Definition: You can parameterize clients with different requests, queue or log requests, and support undo/redo by using the Command pattern, which encapsulates a request as an object.
  • Use-case: Let’s say you wish to allow undo/redo in a text editor that has the following operations: cut, copy, paste, and delete. For every operation, you create a Command object, call undo() on it, and maintain a history stack.
  • Benefits: Queueing, support for macro commands, extension (new commands) without modifying the invoker, and decoupling the object that calls the operation from the one that knows how to carry it out.

What is the Template Method Pattern?

Suggested approach: Define and demonstrate how an abstract class defines the algorithm’s skeleton and how subclasses override steps.

Sample answer:
  • Definition: The Template Method pattern assigns certain steps to subclasses while defining the general structure of an algorithm in an operation. This lets subclasses redefine certain steps of the algorithm without changing its structure.
  • Use-case: Let’s consider you have the following general order for processing a document: open(), parse(), process(), and close(). These steps are called by the final method processDocument() in an abstract class DocumentProcessor. Process() and parse() are overridden by subclasses.
  • Benefits: Encourage extension through inheritance, avoiding code duplication in algorithm structure, and adhering to the DRY principle.

What is the State Pattern, and how is it different from Strategy?

Suggested approach: Describe the state and compare it with the strategy, paying special attention to state-dependent behavior.

Sample answer:
  • Definition: When an object’s internal state changes, it can change its behavior due to the State pattern. The object seems to change its class.
  • Difference from Strategy: In State, the object itself alternates between state implementations as its internal state changes, whereas in Strategy, the client selects the algorithm (strategy) at runtime. While the state is under internal control, strategy is under external control.
  • Use-case: Let’s imagine you have a TCPConnection object that behaves differently depending on whether it is Established, Listening, Closed, etc. The connection switches between each state, which is an object implementing a common interface.
  • Benefits: Makes state transitions clear, eliminates big switch/case blocks on states, and aids the simple extension of new states.

What is the Chain of Responsibility Pattern?

Suggested approach: Describe and show the process by which a request is passed from one handler to another.

Sample answer:
  • Definition: A request can be passed along a chain of handlers using the Chain of Responsibility pattern. Every handler in the chain either responds to the request or forwards it to the next handler.
  • Use-case: Consider you have a logging system with the following levels: DEBUG, INFO, WARN, and ERROR. Before being managed by the proper handler (such as WarningLogger), a request for log(“message”, WARN) travels through a series of handlers. Alternatively, you can forward events through a series of components in a UI event system.
  • Benefits: Decoupling sender and receiver, enabling dynamic handler chain configuration, and simplifying the addition or removal of handlers.

How would you refactor tightly-coupled code using Design Patterns?

Suggested approach: Give an example, describe how to recognize coupling issues, and select patterns to decouple.

Sample answer:

Assume that all of the logic is embedded in a class OrderProcessor that directly generates PaymentService, ShippingService, and NotificationService. Testing and adding new services are challenging due to this close coupling.

Steps in refactoring:
  1. Identify dependencies and give each service an abstraction (interface).
  2. To assign service creation, use Factory or Dependency Injection.
  3. Present the strategy pattern for different payment algorithms.
  4. Present the Observer pattern, which notifies different channels (push, SMS, and email) when an order status changes.
  5. Wrap multiple subsystems (notification, shipping, and payment) under a simpler interface by using Façade (or Façade pattern).

By using these patterns, you can satisfy the SOLID principles, reduce coupling, improve cohesion, and make the system simpler to test and expand.

Conclusion

It takes more than just learning names and definitions to become proficient in design patterns. It involves understanding the issue that the pattern resolves, identifying the situation in which it is suitable, being conscious of the trade-offs, and clearly stating how you would use it in practice.

Utilize the above questions as a guide to help you practice. Review the 20 patterns, work on your capability to explain them clearly, and then practice using them in interview-style situations. That puts you in a good position to impress your next interviewer with your knowledge of design patterns.