Design patterns are reusable solutions to common problems in software design. They provide best practices for structuring code to make it more maintainable, scalable, and flexible. Below are some common interview questions related to Java Design Patterns:
Basic Concepts
- What are design patterns?
- Design patterns are proven solutions to recurring design problems in software development. They provide a template for solving problems in a way that is reusable and maintainable.
- Why are design patterns important?
- They promote code reusability, maintainability, and scalability. They also help developers communicate solutions effectively.
- What are the three main categories of design patterns?
- Creational, Structural, and Behavioral.
Creational Design Patterns
- What is the Singleton pattern?
- The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Example:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- What is the Factory pattern?
- The Factory pattern provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
- What is the Abstract Factory pattern?
- The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- What is the Builder pattern?
- The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
- What is the Prototype pattern?
- The Prototype pattern creates new objects by copying an existing object, known as the prototype.
Structural Design Patterns
- What is the Adapter pattern?
- The Adapter pattern allows incompatible interfaces to work together by converting the interface of one class into another interface that the client expects.
- What is the Decorator pattern?
- The Decorator pattern adds behavior to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class.
- What is the Proxy pattern?
- The Proxy pattern provides a surrogate or placeholder for another object to control access to it.
- What is the Facade pattern?
- The Facade pattern provides a simplified interface to a complex subsystem.
- What is the Composite pattern?
- The Composite pattern composes objects into tree structures to represent part-whole hierarchies, allowing clients to treat individual objects and compositions uniformly.
- What is the Bridge pattern?
- The Bridge pattern separates an object’s abstraction from its implementation so that the two can vary independently.
Behavioral Design Patterns
- What is the Observer pattern?
- The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- What is the Strategy pattern?
- The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to vary independently from clients that use it.
- What is the Command pattern?
- The Command pattern encapsulates a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations.
- What is the Iterator pattern?
- The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- What is the State pattern?
- The State pattern allows an object to alter its behavior when its internal state changes.
- What is the Template Method pattern?
- The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
- What is the Chain of Responsibility pattern?
- The Chain of Responsibility pattern passes a request along a chain of handlers, where each handler either processes the request or passes it to the next handler in the chain.
- What is the Mediator pattern?
- The Mediator pattern defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.
- What is the Memento pattern?
- The Memento pattern captures and externalizes an object’s internal state without violating encapsulation, so that the object can be restored to this state later.
- What is the Visitor pattern?
- The Visitor pattern separates an algorithm from the object structure on which it operates, allowing new operations to be added without modifying the objects.
Real-World Applications
- Give an example of where the Singleton pattern is used in Java.
- The
Runtime
class in Java uses the Singleton pattern to provide a single instance for interacting with the Java runtime environment.
- The
- How is the Factory pattern used in Java?
- The
java.util.Calendar
class uses the Factory pattern to create instances of different calendar types.
- The
- How is the Observer pattern used in Java?
- The
java.util.Observer
andjava.util.Observable
classes (deprecated in Java 9) implement the Observer pattern.
- The
- How is the Decorator pattern used in Java?
- The
java.io
package uses the Decorator pattern extensively (e.g.,BufferedReader
,FileReader
).
- The
- How is the Proxy pattern used in Java?
- Java’s dynamic proxy mechanism (
java.lang.reflect.Proxy
) is an example of the Proxy pattern.
- Java’s dynamic proxy mechanism (
Advanced Topics
- What is the difference between the Factory pattern and the Abstract Factory pattern?
- The Factory pattern creates objects of a single type, while the Abstract Factory pattern creates families of related objects.
- What is the difference between the Adapter pattern and the Proxy pattern?
- The Adapter pattern changes the interface of an existing object, while the Proxy pattern provides a surrogate or placeholder for another object.
- What is the difference between the Strategy pattern and the State pattern?
- The Strategy pattern encapsulates interchangeable algorithms, while the State pattern allows an object to change its behavior based on its internal state.
- What is the difference between the Command pattern and the Template Method pattern?
- The Command pattern encapsulates a request as an object, while the Template Method pattern defines the skeleton of an algorithm in a method.
- What is the difference between the Iterator pattern and the Visitor pattern?
- The Iterator pattern provides sequential access to elements of a collection, while the Visitor pattern separates algorithms from the objects they operate on.
Best Practices
- When should you use the Singleton pattern?
- Use the Singleton pattern when you need exactly one instance of a class to coordinate actions across a system (e.g., logging, configuration).
- When should you avoid the Singleton pattern?
- Avoid the Singleton pattern when it introduces global state, makes testing difficult, or violates the Single Responsibility Principle.
- What are the drawbacks of using design patterns?
- Overuse can lead to unnecessary complexity, and improper use can make the code harder to understand.
- How do you choose the right design pattern for a problem?
- Analyze the problem, identify the recurring patterns, and choose the design pattern that best fits the requirements.
Coding Questions
- Write a Singleton class in Java.
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
- Write a Factory pattern implementation in Java.
interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Square implements Shape { public void draw() { System.out.println("Drawing Square"); } } class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("SQUARE")) { return new Square(); } return null; } }
- Write an Observer pattern implementation in Java.
import java.util.ArrayList; import java.util.List; interface Observer { void update(String message); } class ConcreteObserver implements Observer { public void update(String message) { System.out.println("Received: " + message); } } class Subject { private List<Observer> observers = new ArrayList<>(); public void addObserver(Observer observer) { observers.add(observer); } public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } }