Compound Patterns - The Model View Controller (MVC)
This entry was posted on 12/9/2006 3:45 PM and is filed under Design Patterns.
On December 7, I delivered the final class of my six part Design Patterns class for the Fall 2006 semester of SRA-University on Compound Patterns, specifically the Model View Controller. Design Patterns are often used together and combined within the same design solution. A compound pattern combines two or more patterns into a solution that solves a recurring or general problem.
The Model View Controller (MVC) is an example of a compound pattern. As it's name indicates, it consists of a model, a view, and a controller. Here are each of the participants in the pattern and the functions they provide:
The View gives us a presentation of the model (User Interface). The View asks the model for state and gets its state directly from the Model.
The Controller takes user input and figures out what it means to the model. The Controller asks the Model to change its state. If the client clicks a button, it is up to the Controller to interpret what that means.The controller may also ask the View to change.
The Model notifies the View when its state has changed. This may be based on some action the client takes (like clicking a button) or some other internal change (like the next song in a playlist has started).
The Client interacts with the View. When the Client interacts with the View, the view tells the Controller what the Client did.
I mentioned that the MVC is a compound pattern. It employs the Observer, Strategy, and Composite Patterns. Let's take a look at how this happens.
The Model implements the Observer pattern to keep subscribing objects notified when state changes. Using the Observer pattern, the model is completely independent of the views and the controllers.It allows us to use multiple views with the same model, or even multiple views at once.
The View is an object that is configured with a Strategy. The Controller provides the strategy. The View delegates to the Controller how to handle user actions. The View is only concerned with the visual aspects of the application. The Strategy pattern keeps the View decoupled from the Model.
The View is a composite of GUI elements – buttons, text entry fields etc. The top level component contains other components, which contain other components until you get to the leaf level.
The MVC is employed in Java in the Struts model. It allows developers to divide up work, and also provides loose coupling between logical layers of the application. In the Microsoft world, in the MSDN web site Patterns and Practices section - there are several good articles that refer to Microsoft centric implementations of the MVC. An article containing an overview of the MVC pattern can be found here. Another article that discusses a more specific implementation using the Front Controller Pattern .