First, you need to understand the Observer pattern. The basic idea is that you define an object that notifies interested parties when it changes. (Note that the Observer pattern is a bit more general - Observables notify Observers about "some event". For MVC, that event is "something changed") First you define a contract between the OBSERVABLE and OBSERVER Then you define the OBSERVABLE This allows any other object to "listen" for changes on the thing it's interested in, as long as it implements that observer interface.For example: Creates an instance of the observable (the Person), registers an observer (TestObserver), and then interacts with the Observable. When run, we see So far so good.Now let's call the Person our MODEL. The MODEL represents the data that we want to manipulate and view. We can do this in a "user interface". The user interface can be, but is not limited to:
The user interface (UI) allows a user (a person or another computer for example) to see information about the model and make changes to that information. The "View" is the part of the UI that displays the information for the user. It reads data from the model and formats it in some way to present it. If the model changes, the View must be updated. To accomplish this, it registers observers with the model. Those observers simply refresh the relevant parts of the presentation in the View. Now what happens if the user wants to make a change? We define a "Controller" in the UI as code that interprets user interaction with that UI. For example, if the user types in the "name" field, the controller may interpret that as "change the value of 'name' to the text the user has typed. The controller makes a call to update the model.Remember what that setName() method does? It notifies the observers of the change. This will cause the UI to update its view. Note that "view" and "controller" do not need to be separate classes; they're often combined. It's really the roles of "view" (the part of the UI that displays model data) and "controller" (the part of the UI that interprets user interaction and updates the model) that are important to understand. In some settings, such as Web Applications, the view and controller are very separate. The controller interprets the HTTP requests that are made to the server and updates the mode. The view renders HTML responses to the user. (If you're doing an AJAX application, the design is a bit more similar to a GUI) The cool thing about the MVC separation (Model vs UI) is that you can add or remove UIs from the Model at any time, and can have multiple UIs on the same model. If data is changed in one UI, all other UIs are updated to reflect the change. Cool, eh? |
Sunday, April 1, 2012
MVC nice article with Observable pattern
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment