MVC: update only one time
Hi,
suppose I've this model class:
publicclass MyClassextends java.util.Observable{
public MyClass(){}
//get methods
...
//set methods
...
privateint x;
privateint y;
privateint z;
privateint t;
privateint s;
}
Now I want that, when I use more than one set method, observers are notified only one time.
That is,
if I have this calls:
MyClass obj =new MyClass();
...
obj.setX(1);
obj.setY(2);
obj.setZ(3);
obj.setT(4);
obj.setS(5);
I want that the update method isn't called five times, but only one time.
I can't add setChanged() and NotifyObservers() in only one of the set method,
because I 'm interesting in knowing when the model has been modified.
I thought of adding a new set method like this:
setModified(){
setChanged();
notifyObservers();
}
so, every time I want to notify observers, I run this method.
But, I want to know:
Is this the correct way to do?
Thank you in advance.
MargNat
[1843 byte] By [
MargNata] at [2007-11-26 18:53:07]

# 1
This design smells fishy to me.
If users will always be changing all five values at once, throw out
your five set methods and replace them with
setValues(int x, int y, int z, int t, int s)
You can also use listeners rather than observable, and
fire different events based off of which value changes.
# 2
No,
the five values doesn't always change all at once.
I can have this code in one class:
obj.setX(45);
obj.setY(46);
and in another class this:
obj.setX(45);
obj.setZ(345);
obj.setT(345);
I simply don't want the observers are called many times.
the values are indipendent among them, I don't want to have only one set method for them;
this isn't an object oriented approach.
Practically, I want to know where exactly must be placed setChanged() and notifyObservers() methods.
In all model methods?
In a specific method I can call every time I want to update?
I must call setChanged() and notifyObserver() directly, as example, like:
obj.setChanged()
obj.notifyObservers
?
Thank you again.
MargNat
# 3
obj.setX(0);
System.out.println("Foo");
obj.setY(0);
One notification or two?
obj.setX(0);
Thread.sleep(5000);
obj.setY(0);
One notification or two?
obj.setX(0);
this.myDatabaseAccessMethod("Blah");
this.myOtherMethod("FooBar");
obj.setY(0);
One notification or two?
Do you understand my point?
# 4
Yes,in cases you have mentioned two notifications are good.Repeat, I want to know what is the best and standard way to proceed if I want to notify observers one time, two time, three time, etc., every time I want to do it.MargNat
# 5
public void setX(final int x, final boolean notifyObservers) {
or
myObject.setX(12);
myObject.notifyObservers();
There is no way for your object to tell if client classes put other
lines of code in between method invocations.