Model-View-Controller

Problem

An application usually has three components:

presentation = the user interface

business = the application-specific logic and data

persistence = the files or database where the application-specific data is stored

The presentation component is most volatile (changes frequently) while the business component is most stable (changes infrequently).

For example, in a spread sheet, the logic of a grid of cells containing data and depending on other cells has been around since before computers were invented. During this time we have seen a steady evolution in the user interface from the simple console user interface of VisiCalc to the multi-view, multi-document graphical user interface of Excel. (A personal opinion: we are now seeing the de-evolution of Excel's user interface.)

If the business component depends on the presentation component, then changes to the presentation component will ripple into the business component.

Here's a simple example. Which version is more useful:

double square(double x) {
   double y = x * x;
   printf("The result = %d\n", y);
   return y;
}

double square(double x) {
   double y = x * x;
   return y;
}

Solution

The Model-View-Controller Design Pattern separates the business component (called the model) and the presentation component. The presentation component depends on the model, but not vice-versa:

The business component may contain many classes, but often one class manages the others and serves as a facade to the entire component. This class is called the Model.

The presentation component contains the view class and the controller class. (There may be many views and controllers.) The view class corresponds to the user interface. It contains controls such as menus, buttons, and text fields. Tweaking a control sends a command to the controller, where they are executed.

Here's a typical interaction:

 

Example

In MS Word the role of Model is played by the document. MS Word is a multi-document, multi-view application. The role of view is played by the Word window. There can be several documents open at a time, and there can be several views of a given document open at a time. There are different types of views: normal, outline, print layout. MS doesn't distinguish between views and controller. In other words, the view also play the role of controller.

Example

In a Java application the role of view is usually played by a subclass of JPanel. The role of controller is usually played by an implementation of ActionListener.

Example

In a console user interface, the console plays both, the role of view and controller.

Note

The Entity-Control-Boundary analysis model maps nicely to the Model-View-Controller architecture. Entities map into the business component, while views and controls map to view and controller components, respectively.