Java Model-View-Controller (MVC)

Model-View-Controller (MVC) Structure

Previous – Presentation-Model

Here the same calculator is organized according the the Model-View-Controller (MVC)pattern. The idea is to separate the user interface (the Presentation in the previous example) into a View (creates the display, calling the Model as necessary to get information), and Controller (responds to user requests, interacting with both the View and Controller as necessary). The literature on MVC leaves room for a number of variations, but they all follow this basic idea. This model is simple and can be used with simple method calls. If there are more complex interactions (eg, the Model is asynchronously updated), an Observer pattern (listeners) may be required.

An excellent description of MVC is Sun’s article Java SE Application Design With MVC. Another description of MVC can be found at the beginning of the tutorial Applying the Model/View/Controller Design Paradigm in VisualAge for Java.

Main program

The main program initializes everything and ties everything together.

View

This View doesn’t know about the Controller, except that it provides methods for registering a Controller’s listeners. Other organizations are possible (eg, the Controller’s listeners are non-private variables that can be referenced by the View, the View calls the Controller to get listeners, the View calls methods in the Controller to process actions, …).

The Controller

The controller process the user requests. It is implemented here as an Observer pattern — the Controller registers listeners that are called when the View detects a user interaction. Based on the user request, the Controller calls methods in the View and Model to accomplish the requested action.

Model

The model is independent of the user interface. It doesn’t know if it’s being used from a text-based, graphical, or web interface. This is the same model used in the presentation example.

Copyleft 2004 Fred Swartz MIT License