Design Pattern Interview Questions in Java
Experienced teachers don't invent a new way to run a class test every time; they reuse approaches that have worked for years: a seating plan, a fixed time limit, collecting papers row by row. Design patterns are the programming version: well-known, named solutions to problems that keep coming up in object-oriented code. Interviewers ask about them because patterns are a shared vocabulary. Saying "use a Strategy here" tells a teammate a whole design in three words. This page collects the questions asked most often, with the JDK examples interviewers love to hear.
General Questions
What is a design pattern?
A reusable, named solution to a common design problem, described as a template rather than finished code. The classic catalog is the 1994 "Gang of Four" book, which lists 23 patterns in three groups.
What are the three categories of design patterns?
Creational patterns control how objects are created (Singleton, Factory Method, Abstract Factory, Builder, Prototype). Structural patterns compose classes and objects (Adapter, Decorator, Proxy, Facade, Composite). Behavioral patterns organize responsibilities and communication (Strategy, Observer, Command, Template Method, Iterator).
When should you not use a design pattern?
When the problem is simple and the pattern only adds classes and indirection. Patterns are tools for real problems that keep recurring, not a checklist. Over-engineering is a common code smell.
Creational Patterns
What is the Singleton pattern, and how do you make it thread-safe?
It ensures a class has only one instance with a global access point. The simplest thread-safe forms are an enum with one constant, or a static holder class whose field is initialized when first used. Double-checked locking with a volatile field also works but is easy to get wrong.
What are the drawbacks of Singleton?
It is global state in disguise: it hides dependencies, makes unit testing hard (you can't easily swap in a fake), and can become a bottleneck. Modern code usually prefers passing a single shared instance through constructors (dependency injection).
What is the Factory pattern?
A method or class that creates objects so callers don't use new on concrete classes directly. Callers depend on an interface, and the factory decides which implementation to return. JDK examples: List.of, Calendar.getInstance(), NumberFormat.getCurrencyInstance().
What is the Builder pattern?
A separate builder object that sets optional parts step by step and then builds the final, often immutable, object. It replaces constructors with long lists of parameters. JDK examples: StringBuilder, HttpClient.newBuilder(), Stream.builder().
Structural Patterns
What is the Decorator pattern?
Wrapping an object in another object with the same interface that adds behavior, possibly several layers deep. Java I/O is built on it: new BufferedReader(new InputStreamReader(new FileInputStream(file))).
What is the Adapter pattern?
A class that makes an existing class fit an interface it doesn't implement, like a travel plug adapter. JDK examples: InputStreamReader adapts a byte stream to a character Reader; Arrays.asList adapts an array to a List.
What is the Proxy pattern?
An object that stands in for another with the same interface, controlling access to it: adding security checks, lazy loading, caching or remote calls. Java's java.lang.reflect.Proxy creates proxies at runtime, and frameworks use them for transactions.
Behavioral Patterns
What is the Strategy pattern?
Defining a family of interchangeable algorithms behind one interface and choosing one at runtime. Comparator is the classic JDK example: list.sort(byMarks) or list.sort(byName). With lambdas, a strategy is often just a lambda.
What is the Observer pattern?
Objects (observers) subscribe to another object (the subject) and are notified when it changes. Event listeners in user interfaces, PropertyChangeListener, and publish-subscribe messaging all follow it.
What is the Template Method pattern?
A base class defines the steps of an algorithm in a final method and lets subclasses fill in some steps. AbstractList implements most of List on top of the get and size methods that a subclass provides.
Three Patterns in Code
Let's see Strategy, Builder and an enum Singleton in one program.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Patterns {
record Student(String name, int marks) {}
// Builder: optional parts set step by step
static final class ReportCard {
private final String student;
private final String remark;
private final boolean showRank;
private ReportCard(Builder b) {
student = b.student;
remark = b.remark;
showRank = b.showRank;
}
static Builder forStudent(String student) {
return new Builder(student);
}
static final class Builder {
private final String student;
private String remark = "";
private boolean showRank;
private Builder(String student) { this.student = student; }
Builder remark(String r) { remark = r; return this; }
Builder showRank() { showRank = true; return this; }
ReportCard build() { return new ReportCard(this); }
}
@Override
public String toString() {
return student + (remark.isEmpty() ? "" : " - " + remark)
+ (showRank ? " (rank shown)" : "");
}
}
// Singleton: one instance, thread-safe by design
enum SchoolConfig {
INSTANCE;
int passMark() { return 35; }
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>(List.of(
new Student("Srihitha", 84), new Student("Navika", 91),
new Student("Advitha", 77)));
Comparator<Student> byName = Comparator.comparing(Student::name);
Comparator<Student> byMarks =
Comparator.comparingInt(Student::marks).reversed();
students.sort(byName); // Strategy 1
System.out.println(students.stream().map(Student::name).toList());
students.sort(byMarks); // Strategy 2
System.out.println(students.stream().map(Student::name).toList());
System.out.println(ReportCard.forStudent("Navika")
.remark("Excellent").showRank().build());
System.out.println(ReportCard.forStudent("Advitha").build());
System.out.println("pass mark: " + SchoolConfig.INSTANCE.passMark());
}
}[Advitha, Navika, Srihitha]
[Navika, Srihitha, Advitha]
Navika - Excellent (rank shown)
Advitha
pass mark: 35Explanation:
- The two comparators are strategies:
sortstays the same, and the ordering changes by passing a different object. - The builder lets the caller set only the parts they need; the
ReportCarditself hasfinalfields and no setters, so it is immutable. - The enum singleton is created once by the JVM, is thread-safe without any locking, and can't be duplicated by reflection or serialization.
Interview Corner
Which pattern would you use for different payment methods at checkout?
Strategy: a PaymentMethod interface with pay(amount), implemented by UPI, card and wallet classes, chosen at runtime. A factory can create the right one from the user's selection.
Which patterns do frameworks such as Spring use?
Dependency injection (an alternative to Singleton and Factory), Proxy for transactions and security, Template Method in classes like JdbcTemplate, Observer for application events, and Factory for creating beans.
Practice
- Easy: Add a third strategy to
Patterns.javathat sorts students by the length of their name, then by name. - Harder: Write a small Observer: a
MarksRegisterthat lets listeners subscribe and notifies each one with the student and mark whenever a mark is entered. Add two listeners, one that prints and one that counts failures (below 35).
Key Takeaways
Was this tutorial helpful?