Prev Next

Java / Design Patterns

Last updated

Last updated 19 September 2026. Default examples are mid-level Spring and Java 17–21. Junior and senior sit in labeled sections so the first screen is not a fresher dump.

Design-pattern interviews on a Java shop are Spring-flavored: dependency injection is the strategy and the factory. This hub covers the GoF names you still need and the Spring mapping. It is not a catalog of 50 patterns. Child questions, including filter versus interceptor, stay on their URLs.

Junior

Singleton: one instance. Spring singleton scope is per container, not per JVM if you have two contexts. A static holder singleton is hostile to tests. Prefer the container. Factory: a method or type that creates objects so callers do not new a graph. Spring @Bean methods are factories. Builder: fluent construction for types with many fields; records plus withers cover some of the same ground in 2026.

Strategy: a family of algorithms behind an interface. Inject the interface. That is DI. Observer: events. Spring ApplicationEventPublisher is the polite version. Decorator: wrap a type to add behavior. Servlet Filter is a decorator on the request/response. Proxy: a stand-in that controls access. Spring AOP proxies are how @Transactional works.

Adapter: convert one interface to another. HttpMessageConverter is an adapter between bytes and objects. Facade: a coarse API over a subsystem. Your service layer should be a facade over repositories, not a pass-through with a different name.

Template method: the algorithm skeleton in a base type, steps in subclasses. JdbcTemplate is the name theft: it is a template for JDBC resource handling, implemented with callbacks, not inheritance. Say that; interviewers listen for it.

Mid-level

DI is not a GoF pattern number, but it is the pattern that ate the others in Spring. Constructor injection is composition. Service locator (injecting ApplicationContext and calling getBean) is the anti-pattern unless you are writing a framework extension.

Filter versus interceptor: Filter decorates the servlet request for the whole container. HandlerInterceptor is an MVC hook around a handler. That harvest URL is the deep link. Do not merge those two sentences.

Circuit breaker, retry, and bulkhead are microservices names (Resilience4j). They are not GoF. Call them stability patterns. Interviews mix the vocabularies on purpose.

When a pattern is wrong: a Singleton service with mutable fields, a Factory that is just a static new, an Observer that cannot unsubscribe, a Proxy that hides I/O without a timeout. Patterns are names for trade-offs, not extra classes for a resume.

Immutability and pure functions steal work from Strategy and Command. A record plus a function can replace a six-class Command hierarchy. Use the small design when it is enough.

Senior

Senior design is about boundaries and evolution. Hexagonal architecture is ports and adapters: the same Adapter pattern at system scale. CQRS is two models, not two databases by default. Event sourcing is a log as truth; most Spring shops do not need it.

AOP as a pattern: cross-cutting at the proxy boundary. It fails on self-invocation and on final classes. If the design requires an inner method to be transactional, the design is wrong; split the type.

Concurrency patterns: thread confinement, immutability, work stealing, and the actor model (not native in Java). Virtual threads change the cost of the thread-per-request pattern; they do not make shared mutable state safe.

API design: compatibility is a pattern. Additive change, deprecated fields, and HTTP problem types. A breaking JSON rename is not 'just a DTO'.

Probe yourself

Which Spring feature is a proxy-based Decorator plus interceptor advice?

AOP proxies for @Transactional, @Async, and similar annotations.

Is JdbcTemplate a GoF Template Method?

It solves the same resource-handling problem with callbacks, not inheritance. Say callback template, not subclass hook.

When is Singleton the wrong answer in Spring?

When the bean holds request-specific mutable state. Use a narrower scope or pass state as arguments.

Related questions on this topic are linked below. Read the full answer on the question URL; this hub does not repeat those answers.

Pitfalls interviewers still use

Drawing six UML boxes for Strategy when a single-method interface and two lambdas would do. Java has functions. Use them. The pattern name can still be Strategy; the ceremony does not have to be 1995.

Singleton plus global mutable time or clock. Tests become order-dependent. Inject a Clock. That is still Singleton if the container owns one Clock bean; the test supplies another.

Calling every interface a Facade. A Facade hides a subsystem. An interface with one implementation is just a seam. Both are useful. They are not the same praise word.

Proxy that swallows exceptions or retries without a budget. You have built a failure amplifier. Retry is a pattern with jitter and a limit, not a loop.

Copying GoF names onto Spring annotations without the trade-off. @Transactional is a proxy. If you cannot say what happens on self-invocation, the name did not help you.

For the room: map Filter, DispatcherServlet, HandlerInterceptor, and @Transactional to Decorator or Proxy. Then say when you would not use a proxy (final class, inner call, too much magic). That is a design conversation, not a flashcard.

How to answer in the room

This hub is Spring-flavored patterns, not a GoF recitation. Strategy is a function or a single-method interface. Factory is an object that picks an implementation. Decorator and Proxy wrap an instance; Spring AOP is the latter. Facade hides a subsystem. Adapter makes two APIs talk. If you cannot give a Spring example, you are studying the book, not the job.

@Transactional is a proxy. Self-invocation skips it. final classes and methods resist CGLIB. JDK proxies need an interface. That is Decorator or Proxy applied to a container, not a UML trophy.

HandlerInterceptor and servlet Filter are wrapping patterns at different layers. Filter is the servlet container. Interceptor is MVC. We already used that distinction on a harvest title. Repeat it here with the pattern name if they ask 'which pattern is a Filter'.

Singleton in Spring is the default bean scope, not a private constructor plus a static holder you write yourself. The container owns the instance. Tests replace the bean. A static holder plus mutable clock is how tests become order-dependent. Inject Clock.

Observer is ApplicationEvent and @EventListener. Publish after commit if the listener must not run on rollback. Do not pretend an in-process event is a message bus. If you need Kafka, say Kafka.

Template method is JdbcTemplate and RestTemplate (legacy) and the idea of 'we run the loop, you fill the callback'. Strategy plus a template is how Spring avoids copy-paste around resources. That is a better story than drawing AbstractClass with six hooks.

Refuse to name a pattern when a method would do. Interviewers who like flashcards will push. Answer the trade-off: extra type versus extra magic versus extra runtime proxy. Then stop. This is not a 23-pattern dump.

If they ask for the singleton pattern on a whiteboard, write a Spring @Bean or rely on the default scope. A double-checked lock plus a static instance is a 2005 answer. If they insist on the language-level form, use an enum constant and then say you still would not do that for a service with collaborators.

Interview questions

1. Explain builder pattern in Java.

Builder pattern combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern. To create the desired object, the client first calls a constructor (or static factory) with all of the required parameters and gets a...

Read full answer

2. Explain telescopic constructor pattern in Java.

In Java there is no support for default values for constructor parameters. Telescoping constructor comes to the rescue....

Read full answer

3. Explain Java beans pattern.

Using JavaBeans pattern, you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest as required. private Person person1 = new Person(); person1.setFirstName( "Steve" ); person1.setLastName(...

Read full answer

4. Explain Service Provider framework pattern.

A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations. There are 3 essential components of a service provider framework:...

Read full answer

5. How do we ensure Singleton Design Pattern in a clustered Environment?

Each JVM will have its own copy of singleton object in clustered environment, so we may have to use different techniques to ensure only one instance exists across multiple JVMs in clustered environment. Terracotta, Oracle Coherence provides an in memory...

Read full answer

6. Difference between Front Controller and View Helper in J2EE.

Front Controller is a controller pattern which provides a centralized controller for managing requests. All incoming requests are delegated to front controller first and it is useful when your application has multiple entry points which you want to centralize through...

Read full answer

7. Difference between filter and interceptor patterns in Spring MVC.

A servlet Filter wraps the raw request before DispatcherServlet. A HandlerInterceptor runs around the controller inside Spring MVC and sees HandlerMethod.

Read full answer

8. Difference between Singleton Pattern and static Class in Java.

Singleton pattern gives you an Object, while later just provide static methods. Static class provides better performance than Singleton pattern, because static methods are bonded on compile time....

Read full answer

Next in this series: Github copilot interview questions
«
»

Comments & Discussions