MVC send the entire model or events to the View
I am changing my application to use the MVC pattern. Currently in the notify() method for the observer I am sending the entire model to the View. Is this correct or should be be creating seperate Events and send them to the cl开发者_如何学编程ients?
The Observable
public interface Observable<T> {
void notifyObservers(T model);
void addObserver(Observer<T> o);
void removeObserver(Observer<T> o);
void removeAllObservers();
}
The Observer
public interface Observer<T> {
void notify(T o);
}
The model sends notifications to view like this
@Override
public void notifyObservers(ModelViewInterface model) {
for(Observer<ModelViewInterface> o : this.observers)
o.notify(model);
}
And I notify them like this
notifyObservers(this);
In the ModelViewInterface
I only have the getter methods (no setter methods) and my model implements this interface.
There are a few ways to do this sort of thing. For example, you could:
Send the model with every update, have the view replace its reference with every update. This is ok, especially for a proof of concept. You may run into problems if you distribute your app across a network, as the messages become larger.
Send the delta with every update, have the view update itself based on this delta. This would have the benefit of smaller messages. On a distributed system this might work better, but you need to handle the local model maintenance in the view.
Dont send any of the model with updates to the view, but just tell the view that the model has changed and it should figure out what to do. On a distributed system, you could have the remote and local models work on keeping each other in sync, but the communication between the model and the view is very simple.
精彩评论