The Model-View-Controller Pattern
The Model-View-Controller pattern was created out of a need to cleanly separate the display logic, business logic, and data in an application and to properly coordinate their interactions. Take for example a financial application where the same information can be displayed in two separate documents, one as numeric values and one as a chart. If the data changes, both documents must be automatically updated to reflect the changes.
The MVC pattern has three classes:
The Model represents the underlying data for the application. It can be a series of business objects, or even the database itself.
The View represents the user interface element. It can be a form, a control, or a web page.
The Controller coordinates interaction between the View and the Model. It can validate user-entered data and raise exceptions where necessary. It passes data changes to the Model.
The Model, the View, and the Controller interact with each other using direct method calls and by raising events. The sequence generally follows the following sequence
- The user inputs data into a View
- The View notifies the Controller of a change by using the HandleEvent function
- The Controller modifies the Model directly using its properties
- The Model sends out events to all its observers to inform them of the change
Implementing the MVC pattern implies also implementing the Observer pattern to allow the objects to sending and receive events. The Observer pattern has two classes:
- A Subjectthe source of events.
- an Observerwhich registers with a subject and is notified of changes through events
|Figure 1: The Model-View-Controller implies the implementation of the Observer pattern to coordinate events between classes.|
There are multiple ways to implement the MVC pattern. Patterns are, by their nature, abstract and open to interpretation. This implementation behaves as follows:
- The Model sends events to the View informing it of new or modified data
- The View communicates directly with the Controller to inform it of changes made in the user interface
- The Controller modifies the Model directly to make changes to the data.