Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Explain the mediator pattern, and describe how DispatcherServlet in Spring MVC acts as a mediator.

The mediator pattern puts one object in charge of how a group of objects interact, so the members talk only to the mediator and never refer to each other; many-to-many dependencies become one dependency each, on the mediator. Spring MVC's DispatcherServlet is a mediator: it receives every request and coordinates handler mappings, handler adapters, exception resolvers and view resolvers, none of which call each other, so each can be replaced or added without touching the rest. The risk of the pattern is that the mediator itself grows into a god object.

Why this question is asked

Whenever several components must cooperate, the easy path is to let them call each other directly. With three components that is fine; with eight it becomes a web where every change ripples everywhere. The mediator pattern is the classic answer, and Spring MVC is one of its best-known uses, which is why interviewers pair the two. Understanding it explains how we can plug a custom view resolver or exception handler into Spring without editing anything else. In this answer, we will recap the problem the pattern solves, build a tiny mediator, walk through what DispatcherServlet does for one request, see how replacing a component works, and look at the god object risk.

1A Quick Recap: The Problem of Many-to-Many Dependencies

Imagine a sign-up form with a country drop-down, a postcode field, a terms checkbox and a submit button. The postcode format depends on the country, and the button is enabled only when the postcode is valid and the terms are accepted. If each widget calls the others directly, the drop-down knows the postcode field, the postcode field and checkbox both know the button, and so on. With n components that can each talk to every other, there are up to n x (n - 1) / 2 connections: 6 for four widgets, 28 for eight. Every widget becomes impossible to reuse because it drags its neighbours along.

A mediator is an object that owns those interaction rules. Each component only tells the mediator that something happened, and the mediator decides who else must react. The components now have one dependency each, on the mediator, and the rules live in one readable place.

Java
class SignUpMediator {
private final CountrySelect country;
private final PostcodeField postcode;
private final TermsCheckbox terms;
private final SubmitButton submit;
// constructor wires the four widgets and registers itself with each
void changed(Object source) {
if (source == country) {
postcode.useFormatFor(country.selected()); // "DE" -> five digits
}
submit.setEnabled(postcode.isValid() && terms.isChecked());
}
}
country.select("DE"); // widget calls mediator.changed(this); the postcode format updates
terms.check(); // mediator.changed(terms); submit stays disabled until postcode is valid

Notice that the checkbox does not know a submit button exists. It only reports that it changed. If the product team adds a captcha that must also be solved, we change the mediator's rule and add one widget; none of the others change.

2DispatcherServlet as the Mediator of Spring MVC

Spring MVC needs many components to cooperate on every HTTP request. A HandlerMapping finds which handler, usually a controller method, should handle a request. A HandlerAdapter knows how to invoke that kind of handler, for example resolving method arguments and converting the return value. HandlerExceptionResolvers turn exceptions into responses, which is where @ExceptionHandler methods and @ControllerAdvice plug in. ViewResolvers turn a view name such as "orders" into a template. None of these components knows about the others. DispatcherServlet, the single servlet that receives all requests, calls them in order and passes the results between them.

Java
// A heavily simplified view of what DispatcherServlet.doDispatch does
HandlerExecutionChain chain = getHandler(request); // asks each HandlerMapping in order
HandlerAdapter adapter = getHandlerAdapter(chain.getHandler()); // first adapter that supports() it
ModelAndView mv = null;
Exception failure = null;
try {
mv = adapter.handle(request, response, chain.getHandler()); // runs the controller method
} catch (Exception ex) {
failure = ex;
}
if (failure != null) {
mv = processHandlerException(request, response, failure); // asks HandlerExceptionResolvers
}
if (mv != null) {
View view = resolveViewName(mv.getViewName(), mv.getModel(), locale, request); // asks ViewResolvers
view.render(mv.getModel(), request, response);
}
Step throughOne request through DispatcherServlet
ClientDispatcherServletHandlerMappingHandlerAdapterViewResolver
GET /orders
getHandler(request)
OrderController.list
handle(request, response, handler)
ModelAndView("orders", model)
resolveViewName("orders")
Thymeleaf view
rendered HTML

8 messages in order. Play them, or step through them one at a time.

The dispatcher passes each result to the next component; the components never call each other.

The handler mapping never calls the adapter, and the adapter never calls a view resolver. Each component answers one question asked by the dispatcher: who handles this, how do I call it, what does this error become, which view is this name. The real method also runs HandlerInterceptors before and after the handler and deals with async requests and multipart parsing, but the shape is the same. For a @RestController, the adapter writes the JSON body itself through message converters and returns no ModelAndView, so view resolution is skipped.

3Replacing or Adding a Component

Because every component depends only on its own interface and the dispatcher, we can change one without the others noticing. At startup, DispatcherServlet looks up all beans of each strategy type in the application context, sorts them by their order, and uses them as lists. Adding a bean is enough to join the chain.

Java
@Component
class AuditExceptionResolver implements HandlerExceptionResolver, Ordered {
public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } // asked before the default resolvers
public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse res,
Object handler, Exception ex) {
audit.record(req.getRequestURI(), ex); // only records
return null; // null: let the next resolver decide
}
}

This resolver is picked up, placed early in the list because of its order, and asked about every exception, and returning null hands the decision to the next resolver in the list. Nothing in the controllers, the mappings or the view resolvers changed. In the same way, Spring Boot registers its own view resolvers and message converters, and an application can add one for PDF output without editing any of them. That isolation is precisely what the mediator promises.

4The Risk: The Mediator Becomes a God Object

Moving interaction logic into one place has a cost: that place can attract everything. A god object is a class that knows and does too much, so every change touches it and nobody understands it fully. In our sign-up example, if the mediator grows to handle validation messages, analytics events, saving drafts and A/B tests, it becomes the hardest class in the codebase.

DispatcherServlet avoids this through discipline that is worth copying. It coordinates but does not decide: the decision of which handler, how to call it and what view to render is delegated to pluggable strategies. It holds no business logic at all. So the advice for our own mediators is to keep them to sequencing and routing, delegate each real decision to a small collaborator, and split the mediator when it starts serving two unrelated groups of components.

5Follow-up questions

How is a mediator different from an observer or event bus?

With an observer, a subject broadcasts events and does not know what listeners do; the interaction rules are spread across the listeners. A mediator knows its colleagues and contains the rules explicitly, so the coordination is readable in one class. An event bus sits in between: it routes messages by type, but the rules stay spread over handlers.

Is DispatcherServlet also a front controller?

Yes. Front controller is the web pattern name for a single entry point that receives all requests and dispatches them, and DispatcherServlet is one. The two descriptions look at different aspects: front controller describes its place at the edge of the application, mediator describes how it coordinates the internal strategies without them knowing each other.

What happens if no HandlerAdapter supports the handler?

DispatcherServlet throws a ServletException saying no adapter was found for the handler. It usually means a custom handler type was registered without its adapter, which is another illustration of the pattern: the dispatcher needs one component of each role, and the roles are matched only through the dispatcher.

6Conclusion

In this answer, we saw that a mediator centralises how a group of objects interact, replacing up to n x (n - 1) / 2 direct links with one dependency per component. DispatcherServlet plays this role in Spring MVC: it asks handler mappings, handler adapters, exception resolvers and view resolvers one question each and passes results between them, so they never call each other and any of them can be replaced or added as a bean. We also saw that a mediator must stay a coordinator, delegating decisions, or it turns into a god object.

What to say in the interviewAbout 80 seconds aloud

Open with

The mediator pattern puts the interaction rules of a group of objects in one place. Instead of components calling each other, each one only tells the mediator something happened, and the mediator decides who reacts.

Then, if they want more

That turns a many-to-many web of dependencies into one dependency per component on the mediator, so components can be reused and changed independently. In Spring MVC, DispatcherServlet is a mediator.

For each request it asks the handler mappings which handler matches, asks the handler adapters which one can invoke it, calls it, sends any exception to the handler exception resolvers, and passes a view name to the view resolvers. None of those components knows the others; they only answer the dispatcher's question.

That is why I can add a custom exception resolver or a view resolver just by declaring a bean, and nothing else in the application changes, because the dispatcher discovers all strategy beans and uses them in order. The main risk of the pattern is that the mediator becomes a god object that knows everything.

DispatcherServlet avoids that by coordinating only and delegating every real decision to the strategies, and I try to keep my own mediators the same way.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the mediator pattern, and describe how DispatcherServlet in Spring MVC acts as a...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/a551a2464f/