Model-View-Controller Pattern

COMP 310  Java Resources  Eclipse Resources

(Back to Design Patterns)

A program can often be divided into two parts:

The view takes the user input and passes the information onto the model. The model outputs information to the view, which then presents it to the user. In the spirit of loose coupling the following ideals should be enforced:
This has the following implications:
Therefore, what we need is one more component, the "Controller". The controller "knows" about both the specific model and specific view being used. The controller's job is:

The Model-View-Controller ("MVC") design pattern decouples the model from its view, enabling loose coupling and the ability to change one without affecting the other.

Figure 1: MVC pattern showing how the view and model are decoupled.
Block diagram of the MVC pattern
Block diagram of the MVC pattern

To communicate from the model to the view and vice versa, the Adapter Design Pattern is used. In short, an adapter is an interface that one object has defined for use in communicating with another, possibly multiple, objects when it does not know exactly what sorts of object(s) to which it is communicating. Consider the power adapters used to enable one's electronic devices to plug into the electrical power outlets in various foreign countries. The adapter instance used at any given moment is one that is specifically created to connect to the desired target object. The calling object is unaware of and thus decoupled from the object to which the adapter is connected. The model-view-controller pattern, the model and view each hold adapters to each other, where each side has defined an adapter interface that provides the services needed by that side.

The model and view each define their OWN adapter interface(s) as per the services that each needs, irrespective of whatever methods are available on the view or model to which the adapter connects! Each side is designed INDEPENDENTLY. It is the job of the Controller to instantiate the proper implementation of each adapter such that it is able to connecd to the actual model and view types in use.

Multi-piece Models and Views

Often the model is not a single monolithic piece, but rather a collection of loosely coupled sub-models. One can still use a MVC pattern without resorting to encapsulating the submodels into a single model object by considering this:

To any given sub-model, the rest of the sub-model pieces are simply part of its view.

Likewise, the same ideas apply if the view is broken into sub-views.

Thus, the controller can treat the sub-model pieces and the sub-views equivalently. The controller simply is tasked to hook all the pieces together to form a cohesive total program.

 


Originally published in Connexions (CNX): https://web.archive.org/web/20130105081123/http://cnx.org/content/m26104/latest/

 

© 2023 by Stephen Wong