Question

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.

Was it helpful?

Solution

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,

  • Placing the notifyObservers(...) method in the setter methods of all bound properties (all variables that you want to make listenable.
  • Only change the bound properties through their setter methods.
  • You don't even have to pass the bound property inside of the notifyObservers method. If you desire, you could pass through a null, where you notify the observers that a change in state has occurred, and then the observers can call the getter methods that they are interested in to assess the state of the observed object.
  • Consider using PropertyChangeSupport and PropertyChangeListeners instead where you give each bound property its own String constant, and pass into the notification parameter, this String, the old value and the new value. This is what I usually end up doing myself.

Edit
You mention this as a possible solution:

notifyObservers(this);

but I would avoid this as your observers already will receive this information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top