Building a Central Controller

As an architecture, MVC is a good start and suitable for many applications. But sometimes more advanced processing is called for, so it’s time to start filling in the holes in the MVC architecture, starting with the controller. Not only is the controller the first point of contact for requests, it is also the place where we have the most programming and design freedom. Unlike the model, which is shaped by the underlying data, the controller is designed from start to finish as a part of the presentation tier. And unlike the view, which is stateless and generally focused on presentation, we are free to perform as much complicated logic as we like.

The MVC pattern does not specify how many controllers there should be. In our previous example, we built a controller that handled the input from a single screen. In order to extend our application along those same lines, we would have to add new screens and an equal number of new controllers. Alternatively, we could build a single, omniscient controller. This controller would know about every possible request and how to generate a response to each.

Since we are interested in building extensible software, it’s obvious that neither of these solutions is exactly right. Building an entire new controller for each screen does not just mean lots of classes, it makes the application harder to extend. If we wanted to build a logging mechanism, for example, we would have to add logging code to each controller separately. ...

Get J2EE Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.