views:

196

answers:

1

Say you have 5 or 6 variables in the model which a certain View is interested in, do you write different functions for each, such as

int a;
int b;
int c;

void setA( newA ) {
   a = newA;
   notifyAObservers();
}

void setB( newB ) {
   b = newB;
   notifyBObservers();
}

void setC( newC ) {
   b = newC;
   notifyCObservers();
}

Or do you just have one notify method and waste a little bit of CPU time

i.e. instead of notifyAObservers and notifyBObservers, you just have notifyObservers

+4  A: 

I believe the traditional approach is to notify all observers, and let them handle it. This is because you don't know which observers are observing which variable(s) - you just know that they want to be notified when something changes. However, if you do know what observers are observing which variables, and performance is critical, then you might be able to do something like what you have.

In the traditional Observer pattern, the Observers implement an update() method that is called by the controller when a change happens. The Observables (the data model) would have a notifyObservers() method that iterates over the Observers and calls their update() method. Then, the Observers get whatever they need and the view updates.

Any time I have implemented the Observer pattern, however, I simply keep a list of observers and notify them all. That way, I only have one list of observers and the rest of the class as well as the different observers can all change without me making any changes to the observable class notification.

Thomas Owens
It also keeps things simple, since there are ways of finding out which observers are observing which variable. This could end up looking complicated, however.
indyK1ng
Could you give me a quick example Thomas? I have voted you up, but what methods would be implemented in the View, how would they be notified, etc. Thanks!
DevDevDev
Do you mean that all Observers would just implement a "notify()" method, and then they would poll the Model for the data that they are interested in everytime. For instance, notifyObservers() just straight iterates through the list of Observers and calls notify(). Each observer pulls the data it wants from the model and updates it's view accordingly. Like if variable A was changed, the B-Observers would still get a notify() call, and would say something likeb = model.getB(), even though b hasn't changed?
DevDevDev
I'm not sure what you are looking for - the link in my post has examples of the Observer pattern in Java and Python. Could you elaborate on any specific questions you have?
Thomas Owens
Did you read my 2nd comment?
DevDevDev
You posted your second comment when I was posting mine. But yes, you are correct. I did add this to my original post, as well.
Thomas Owens