Reputation: 1135
In java, you can have the model extend the Observable class and the view implement the Observer interface in order to implement MVC with observer pattern such as:
public AppView implements Observer{
public void update(Observable arg0, Object arg1) {
System.out.println((int)arg1);
}
}
public AppModel extends Observable{
public void doStuff(){
x = x +1;
setChanged();
notifyObservers(x);
}
}
Now, the example above has no problems when the model only needs to update one variable to the view. Things usually get ugly or complicated when I need to notify the view of changes of more than 1 variables. Is there a clean way to solve this problem? An example would be I need to notify changes of an integer value and of strings.
EDIT
I know of a few solutions to handle this. I just want your opinions on what would be the best approach.
An answer would be:
notifyObservers("x");
this would tell the view to update x. Another would be for the model to pass itself
notifyObservers();
And the view would check the values. If you have other approaches they are welcome.
Upvotes: 1
Views: 389
Reputation: 285405
I'm not sure what you mean by things getting "ugly", when listening to more than one variable. I'm no expert in MVC, but consider,
notifyObservers(...)
method in the setter methods of all bound properties (all variables that you want to make listenable.Edit
You mention this as a possible solution:
notifyObservers(this);
but I would avoid this as your observers already will receive this information.
Upvotes: 2