21 Software Design Pattern Interview Questions and Answers
Design patterns are important topic for Java interviews, here are common design pattern questions you can prepare for interviews.
Hello folks, if you are preparing for Java Developer Interviews then you should prepare about Software design questions. As a Java programmer who has been through many interviews, I understand how important it is to have a solid grasp of design patterns, not just for interview but also for writing clean code in Java.
They are an essential part of software engineering and can greatly improve the efficiency and maintainability of code. However, many interviews will test your knowledge of design patterns to assess your ability to solve complex problems and design scalable and robust systems.
In my earlier article, I have shared 25 Advanced Java questions, 25 Spring Framework questions, 20 SQL queries from Interviews, 50 Microservices questions, 60 Tree Data Structure Questions, 15 System Design Questions, and 35 Core Java Questions and 21 Lambda and Stream questions which you can use for your Java interview preparation.
In this article, I have compiled 21 common software design pattern questions that you might encounter during a Java interview. By going through these questions and answers, you will be better equipped to tackle any design pattern questions that come your way and increase your chances of success in your next Java interview.
By the way, if you are new to Java programming language or want to improve Java skills then you can also checkout following best Java courses to get better:
- The Complete Java Masterclass (covers Java 17)
- Java Programming and Software Engineering Fundamentals Specialization Certificate on Coursera
- Java Programming Bootcamp: Zero to Mastery
- The Complete Java Programming Masterclass! [Karpado]
- CodeGym (learn Java by building Games)
These are my favorite online courses and platforms to learn Java from scratch and also build your Java skills. If you need more advanced courses to take your Java skill to next level you can also see following articles:
21 Software Design Pattern Interview Questions with Answers
In this article, I have compiled a list of 21commonly asked design pattern questions that can help prepare aspiring Java developers for technical interviews.
These questions cover a broad range of design patterns, including the Singleton, Factory, Observer, and Decorator patterns, among others. By providing detailed explanations of each pattern, along with examples of how they can be implemented in Java, we aim to provide readers with a comprehensive understanding of these important concepts.
Whether you are a novice Java developer or an experienced professional, our list of design pattern questions will prove to be a valuable resource in your preparation for technical interviews.
So, without further ado, let’s dive into the world of design patterns and explore some of the most frequently asked questions related to them.
1. What is difference between Builder and Factory Pattern?
This kind of questions are very common on Java interviews where interviewer test your understanding of patterns. While both Builder and Factory pattern are used to create objects and they are creational design pattern there is a key difference between them.
Builder pattern expose the creation logic and allows you to create the object as you want by supplying additional/optional properties and then calling build() method but Factory pattern doesn’t expose the creation logic, its hidden inside getInstance() method.

2. When will you use Factory or Builder Design pattern?
As I said, factory pattern is used when you want to create object without exposing creation logic while Builder pattern is used when constructor accept too many arguments and most of them are optional.
In other words, the Builder pattern is used when we want to create objects that require the step-by-step initialization of many attributes.
The Builder pattern provides a way to create an object by calling a series of methods that set the required attributes. It’s useful when we have a complex object with many attributes that need to be initialized in a particular order.
3. You are coding a class which is responsible for sending HTTP request to external clients and you know that other applications will use it? What design consideration will you make while designing/coding this class?
This question is normally asked to experienced developer to see how much coding they have done and whether they remember best practices while coding or not. They key here is modularity because your code should be easy for other modules and app to be reused.
For example, when designing a class that is responsible for sending HTTP requests to external clients, there are a number of design considerations that should be taken into account for example:
- Separation of Concerns The class should be designed to focus on sending HTTP requests and handling the response, while delegating other concerns (such as data validation and processing) to other classes or components.
- Encapsulation The class should encapsulate the HTTP request and response logic to promote modularity and maintainability. This will allow other parts of the application to use the class without having to worry about the implementation details.
- Configuration The class should be designed to allow for flexible configuration of parameters such as timeouts, retries, and connection settings. This will allow other applications to easily customize the behavior of the class to suit their needs.
- Error Handling The class should be designed to handle errors and exceptions gracefully, and provide clear and informative error messages to users. This will help to ensure that other applications can easily diagnose and fix any issues that arise.
- Performance The class should be designed to be efficient and performant, minimizing latency and resource usage as much as possible. This will help to ensure that other applications can make use of the class without encountering performance issues.
- Security The class should be designed to ensure the security of any sensitive information that is transmitted through HTTP requests. This may involve using encryption and authentication mechanisms, as well as complying with any relevant security standards or regulations.
- Testing The class should be designed to be easily testable, with appropriate unit and integration tests to ensure that it functions correctly and meets the requirements of other applications that use it.
By taking these design considerations into account, the resulting class you will create will be more robust, maintainable, and flexible, and can withstand test of time on production.
4. What are design patterns in software engineering and why are they important?
Design patterns are nothing but reusable solutions to commonly occurring software design problems like flexibility, scalability, performance, security etc.
They provide a structured approach to solve problems, improve code quality, and make software more maintainable, extensible, and scalable. By learning and applying design patterns, developers can write better code in less time.
5. What is the difference between a creational, structural, and behavioral design pattern?
GOF Patterns or object oriented patterns are divided into 3 main categories, creational, structural and behavioral. As the name suggests, Creational patterns deal with object creation mechanisms, trying to create objects in a manner suitable for the situation.
Structural patterns deal with object composition, simplifying the way objects relate to one another. Behavioral patterns deal with communication between objects, defining the way objects collaborate and interact to achieve specific tasks.
6. Can you explain the Singleton design pattern in Java?
The Singleton pattern is a creational pattern that ensures that a class has only one instance and provides a global point of access to it. The instance is created lazily, the first time the getInstance() method is called.
The best thing about this patter is that provide a clear and controlled access point to a single instance, and avoiding duplicate object creation.
On the flip side, its now treated as anti pattern because of difficulty in testing, potential for violating the Single Responsibility Principle, and issues with concurrent access.

7. What is the Factory Method design pattern and how is it used in Java?
The Factory Method design pattern is a creational pattern that provides an interface for creating objects but allows sub-classes to decide which class to instantiate.
In Java, it is implemented using an abstract creator class that defines the factory method and a concrete subclass that implements the factory method to create the desired objects.
Advantage of this Software design pattern include encapsulating object creation and providing extensibility, while cons include complexity and a potential for creating too many sub-classes.

8. What is difference between a Factory and Abstract Factory pattern in Java?
The Factory Method and Abstract Factory design patterns are both creational patterns that provide ways to create objects. However, they have some key differences in their approach to object creation.
The Factory Method is a design pattern that provides an interface for creating objects in a super-class, but allows subclasses to alter the type of objects that will be created.
This is achieved by defining a factory method in the superclass that returns an object of a specific type, and then overriding this method in sub-classes to return objects of a subclass-specific type.
The Abstract Factory pattern, on the other hand, provides a way to create families of related or dependent objects without specifying their concrete classes.
This is achieved by creating an abstract factory class that defines a set of methods for creating objects, and then implementing these methods in concrete factory classes.
The concrete factory classes return objects of a specific type, and clients use these objects through the abstract factory interface.
In summary, the Factory Method pattern focuses on creating objects of a single type, while the Abstract Factory pattern focuses on creating families of related objects. The choice between the two patterns depends on the specific requirements of the software system being developed.
Here is a nice diagram which also show the difference between abstract and factory design pattern:

9. Can you explain the Abstract Factory design pattern in detail for Java?
The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. In other words, it allows you to create objects that are related to each other or have dependencies, but without specifying the actual classes of those objects.
The main goal of the Abstract Factory pattern is to provide an interface for creating families of objects that can be used interchangeably. This can be useful when you want to create a set of related objects that can be easily swapped in and out of your application without affecting its overall behavior.
The Abstract Factory pattern is often used in situations where the client code needs to be decoupled from the object creation process.
For example, suppose you have an application that needs to generate reports. The reports can be generated in different formats, such as HTML, PDF, or CSV.
You could create a ReportGenerator interface that defines a method for generating reports. Then you could create three different factories that create object of different ReportGenerator based upon format.
10. Can you explain the Prototype design pattern in Java? When to use it?
The Prototype design pattern in Java allows creating new objects by cloning existing objects instead of creating new ones from scratch. It’s useful when the object creation process is expensive and time-consuming. The pattern provides an efficient way to create multiple copies of an object while reducing the cost of object creation.
11. What is difference between Adapter and Bridge pattern?
The Adapter and Bridge design patterns are used to decouple an abstraction from its implementation. However, there are some differences between them.
The Adapter pattern is used to convert the interface of a class into another interface that the client expects. It allows two or more incompatible interfaces to work together.
The Adapter pattern can be used when we have an existing class, and we want to use it with other classes that have a different interface. We create an adapter class that implements the target interface and uses the existing class to implement the interface methods.
The Bridge pattern is used to separate the abstraction from its implementation so that they can vary independently. It is used when we want to change the implementation of a class without affecting its interface.
The Bridge pattern consists of two layers of abstraction: the abstraction layer and the implementation layer. The abstraction layer provides the high-level interface, and the implementation layer provides the low-level implementation details.
In summary, the Adapter pattern is used when we want to make two incompatible interfaces work together, while the Bridge pattern is used when we want to separate the interface from its implementation.
12. What is the Composite design pattern and how is it used in Java?
The Composite pattern is a structural design pattern that allows you to treat a group of objects as a single object. In other words, it lets you create a tree structure of objects and work with the tree as if it were a single object.
In the Composite pattern, there is a “composite” class that contains a collection of “component” objects. The component objects can be other composites or leaf nodes (objects that have no children). Both composites and leaf nodes implement a common interface, so they can be treated the same way by client code.
The Composite pattern is useful when you need to represent a hierarchical structure of objects and want to be able to treat individual objects and groups of objects uniformly. It also allows you to add and remove objects from the hierarchy dynamically at runtime.
In Java, the Composite pattern can be used to represent a file system, where a directory can contain files and other directories. The composite class would be the directory, while the component classes would be the files and sub-directories.
Here’s an example of how the Composite pattern might be implemented in Java:
interface FileSystemItem {
public String getName();
public void print();
}
public class File implements FileSystemItem {
private String name;
public File(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void print() {
System.out.println("File: " + name);
}
}
public class Directory implements FileSystemItem {
private String name;
private List<FileSystemItem> items = new ArrayList<>();
public Directory(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(FileSystemItem item) {
items.add(item);
}
public void remove(FileSystemItem item) {
items.remove(item);
}
public void print() {
System.out.println("Directory: " + name);
for (FileSystemItem item : items) {
item.print();
}
}
}In this example, the FileSystemItem interface is the common interface implemented by both files and directories. The File class is a leaf node, while the Directory class is a composite that can contain other FileSystemItem objects. The print method prints out the name of the file or directory, as well as the names of any child items if it's a directory.
13. Can you explain the Decorator design pattern in Java? When did you used Decorator pattern in your code?
The Decorator pattern is a structural design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
In this pattern, a decorator class wraps the original class, and it provides additional functionality keeping class methods signature intact. This pattern is often used when we have to add functionality to an object at runtime, dynamically.
The following is an example of the Decorator pattern in Java, where we have an interface Pizza and concrete implementation of that interface PlainPizza. We want to add extra functionality to the PlainPizza like cheese or Mushroom topping using decorators, so that we can create different types of pizzas at runtime.
// Pizza interface
public interface Pizza {
public String getDescription();
public double getCost();
}
// PlainPizza class
public class PlainPizza implements Pizza {
public String getDescription() {
return "Plain Pizza";
}
public double getCost() {
return 4.00;
}
}
// ToppingDecorator abstract class
public abstract class ToppingDecorator implements Pizza {
protected Pizza pizza;
public ToppingDecorator(Pizza pizza) {
this.pizza = pizza;
}
public String getDescription() {
return pizza.getDescription();
}
public double getCost() {
return pizza.getCost();
}
}
// CheeseTopping concrete decorator class
public class CheeseTopping extends ToppingDecorator {
public CheeseTopping(Pizza pizza) {
super(pizza);
}
public String getDescription() {
return pizza.getDescription() + ", Cheese Topping";
}
public double getCost() {
return pizza.getCost() + 1.00;
}
}
// MushroomTopping concrete decorator class
public class MushroomTopping extends ToppingDecorator {
public MushroomTopping(Pizza pizza) {
super(pizza);
}
public String getDescription() {
return pizza.getDescription() + ", Mushroom Topping";
}
public double getCost() {
return pizza.getCost() + 2.50;
}
}In the above code, PlainPizza class implements Pizza interface, which has two methods getDescription() and getCost(). ToppingDecorator abstract class implements the Pizza interface and provides a reference to the Pizza interface. The CheeseTopping and MushroomTopping classes are concrete decorators that extend the ToppingDecorator abstract class and add additional functionality.
We can create different types of pizzas with different toppings at runtime as follows:
// Create a plain pizza
Pizza pizza = new PlainPizza();
// Add cheese topping
pizza = new CheeseTopping(pizza);
// Add Mushroom topping
pizza = new MushroomTopping(pizza);
// Print the pizza description and cost
System.out.println(pizza.getDescription());
System.out.println(pizza.getCost());The output will be:
Plain Pizza, Cheese Topping, Mushroom Topping
7.5We can add more toppings dynamically by creating new concrete decorator classes. This way, we can add or remove functionalities at runtime without affecting the underlying class.
The Decorator pattern is very useful when we have a large number of different combinations of object features, and it allows us to create these combinations dynamically.
14. When should you use Facade design Pattern?
You should use the Facade design pattern when you have a complex system with many different parts, and you want to provide a simplified interface for clients to interact with the system.
The Facade pattern provides a single, high-level interface that encapsulates the complexities of the underlying system and makes it easier for clients to use.
This pattern can also help to reduce coupling between the client and the system, since the client only needs to interact with the facade, rather than directly with the various components of the system.
The Facade pattern is especially useful when you need to refactor a large and complex code-base, since it allows you to introduce a simplified interface without having to change the underlying implementation.

15. Can you explain the Flyweight design pattern in Java? When did you used it?
The Flyweight design pattern is used to reduce memory usage by sharing data across objects. It involves separating intrinsic and extrinsic object data, and using shared objects to represent the intrinsic data. I have not personally used it, but it can be used in scenarios where a large number of objects need to be created and memory usage needs to be optimized.
16. What is the Proxy design pattern and how is it used in Java?
The Proxy design pattern provides a surrogate or placeholder for another object to control access to it.
In Java, this pattern is used to provide a layer of indirection to an object, so that clients interact with the proxy instead of the real object. This can be used to implement access control, logging, or remote communication, among other things.

17. Can you explain the Chain of Responsibility design pattern in Java?
The Chain of Responsibility design pattern is a behavioral pattern that allows a request to be passed through a chain of handlers until one of them handles the request. Each handler in the chain has the opportunity to handle the request or pass it on to the next handler. It helps to achieve loose coupling between sender and receiver.
18. What is the Command design pattern and how is it used in Java?
The Command design pattern encapsulates a request as an object, thereby allowing you to parameterize clients with different requests, queue or log requests, and support un-doable operations.
In Java, the command pattern is used for event handling, multi-level undo-redo, thread pools, and more.
It also promotes loose coupling between request sender and receiver, and allows for extensibility of commands.

19. Can you explain the Interpreter design pattern in Java? When to use it? What are its pros and cons?
The Interpreter design pattern provides a way to define the syntax of a language and interpret sentences or expressions in that language. It is useful for implementing compilers or for processing expressions in domain-specific languages.
The pros of this pattern are its extensibility, ease of use, and modular design. However, it can be difficult to implement and may not perform well for complex or deeply nested expressions.
20. What is the Iterator design pattern and how is it used in Java? When did you use it? What are its pros and cons?
The Iterator design pattern provides a way to traverse a collection of objects in a standardized way without exposing the underlying implementation.
In Java, the Iterator interface is used to implement this pattern. It allows the client to access elements of a collection sequentially without knowing the internal structure of the collection.
I have not used the Iterator pattern personally but it can be used to implement a custom pagination logic for a web application.
The pros of using this pattern include separation of concerns, flexibility, and abstraction. The cons include added complexity and potential performance overhead due to the additional abstraction layer.

21. When to use the Mediator design pattern in Java?
The Mediator design pattern is useful when you have a set of objects that interact with each other in complex ways, and you want to avoid tight coupling between those objects. This pattern promotes loose coupling by allowing objects to communicate through a central mediator, rather than directly with each other.
Here are some common scenarios where you might want to use the Mediator design pattern in Java:
- When you have a set of objects that need to interact with each other in complex ways, and you want to avoid tight coupling between those objects.
- When you have a large number of objects that need to communicate with each other, and you want to simplify the communication process.
- When you want to provide a central point of control for your application’s behavior, and you don’t want individual objects to have too much control over the system.
- When you want to be able to modify the behavior of your application at runtime, by swapping out the mediator with a different implementation.
An example of the Mediator design pattern in action might be a chat room application, where multiple users need to communicate with each other. Rather than having each user communicate directly with every other user in the chat room, the application might provide a central mediator that manages all of the communication between users.
The mediator might handle tasks like routing messages, enforcing rules for participation, and maintaining a list of active users. By using the Mediator pattern, the chat room application can be more flexible and easier to maintain, since each user doesn’t need to be aware of all the other users in the room.
22. What is the Observer design pattern and how is it used in Java?
The Observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
In Java, the Observer pattern is implemented using the built-in interfaces Observer and Observable. The Observable class represents the object being observed, while the Observer interface represents the objects that are observing the Observable.
To use the Observer pattern, you first define an Observable object and its corresponding Observer objects. The Observable object maintains a list of its observers, and when its state changes, it calls the notifyObservers() method to notify all its observers of the change. The Observer objects implement the update() method, which is called by the Observable object to update the observer with the new state.
For example, suppose you have a Stock class that represents a stock in a stock market. You could define an Observable subclass called StockMarket that maintains a list of Stock objects and notifies its observers when the prices of these stocks change.
You could then define an Observer interface called StockObserver that defines the update() method, which is called by the StockMarket object to update the observer with the new stock prices. Finally, you could define a Trader class that implements the StockObserver interface and receives notifications from the StockMarket object when the prices of the stocks it is interested in change.

Java and Spring Interview Preparation Material
Before any Java and Spring Developer interview, I always use to read the below resources
Grokking the Java Interview
Grokking the Java Interview: click here
I have personally bought these books to speed up my preparation.
You can get your sample copy here, check the content of it and go for it
Grokking the Java Interview [Free Sample Copy]: click here

If you want to prepare for the Spring Boot interview you follow this consolidated ebook, it also contains microservice questions from spring boot interviews.
Grokking the Spring Boot Interview
You can get your copy here — Grokking the Spring Boot Interview

That’s all about the common Software Design Pattern Interview Questions for experienced developers. If you have worked in Java for long time then you can easily answer these questions but if you found yourself struggling to answer these questions then you should join Design Pattern courses and read Design Pattern books to improve your knowledge.
design patterns are an important aspect of software development and are frequently discussed in Java interviews. It is important for Java programmers to have a good understanding of design patterns and be able to apply them in their work.
By practicing these 21 interview questions related to Software design patterns, you can enhance your knowledge and prepare yourself for your next Java interview. Remember to keep learning and honing your skills, and you will be better equipped to excel in your career as a Java programmer.
By the way, if you are new to Java programming language or want to improve Java skills then you can also checkout following best Java courses to get better:
- The Complete Java Masterclass (covers Java 17)
- Java Programming and Software Engineering Fundamentals Specialization Certificate on Coursera
- Java Programming Bootcamp: Zero to Mastery
- The Complete Java Programming Masterclass! [Karpado]
- CodeGym (learn Java by building Games)
These are my favorite online courses and platforms to learn Java from scratch and also build your Java skills. If you need more advanced courses to take your Java skill to next level you can also see following articles:
Additionally, you can also prepare Microservices Questions like difference between API Gateway and Load Balancer, SAGA Pattern, and Spring Framework questions like Controller vs Rest Controller.





