Saturday, April 25, 2009

Model View Controller





Most of the applications get data from a data store and display it to the user. And if the user changes the data, the data store is updated.



UI <--> Data



Problem



If Data and UI are coupled,



1. UI changes more frequently than the data stored in the system.

2. Business logic gets in UI



Model is an object that represents some information about the domain. It's a nonvisual object containing all the data and behavior other than that used for the UI.



The view represents the display of the model in the UI. The view is only about display of information; any changes to the information are handled by the controller. The controller takes user input, manipulates the model, and causes the view to update appropriately. In this way UI is a combination of the view and the controller.



There occurs two separations



1. Presentation from model



Besides other advantages, it allows for easy testing of domain logic.



Principle : The presentation depends on the model but the model doesn't depend on the presentation.



This principle introduces a common issue. With a rich-client interface of multiple windows it's likely that there will be several presentations of a model on a screen at once. If a user makes a change to the model from one presentation, the others need to change as well. To do this without creating a dependency you usually need an implementation of the Observer pattern. The presentation acts as the observer of the model.



2. View from controller



Separation required to support editable and noneditable behavior, which you can do with one view and two controllers for the two cases, where the controllers are strategies for the view. In practice most systems have only one controller per view, however, so this separation is usually not done.