View Single Post
  #2 (permalink)  
Old 04-01-2008, 05:14 AM
jegan jegan is offline
D-Web Sr.Programmer
 
Join Date: Jul 2007
Posts: 161
jegan is on a distinguished road
Default Re: Model View Controller

How It Works

First you write a Model that extends java.util.Observable. You give your class accessors to get informtion about its current state and you write mutators to update the state. Each mutator should call setChanged() and one or the other of notifyObservers() after it has actually changed the state. NotifyObservers will send an update message to each registered observer (View). There are versions of notifyObservers that let you pass additional information about the change as well.

Then you can create one or more views. Each view must implement the java.util.Observer interface and hence implement the update method. The Object in the second parameter will be used to receive additional information if passed.

interface Observer
{ void update(Observable t, Object o);
}

The View should implement the update method by querying the model (actually the Observable t) for the changes it needs and then make appropriate changes to the view itself.

The View also needs to register with the Model it wishes to observe by sending the model the addObserver message. The Model will remember all registered views so that it can notify (update) them later.

The reason that a Model has to extend java.util.Observable is that the Observable class provides all of the register/notify infrastructure needed by a model, so you don't have to build any of this and can concentrate on the functionality of your application.

A model can have several views. MVC was created specifically to permit this. Also, a view can register with several models and get updates from each of them.

It isn't necessary to build your Model so that it is a single Observable. Instead, several parts of the model can be separately Observable, each part with its own Observers.
__________________
Thanks & Regards,
Jegan CBK
"We will either find a way, or make one!”
Reply With Quote