How to detect if a variable has changed?
I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:
int x = 1;
int initialx = x;
...//code that may or may not change the value of x
if (x!=initialx){
doOneTimeTaskIfVariableHasChanged();
initialx = x; //r开发者_StackOverfloweset initialx for future change tests
}
Is there a better/simpler way of doing this?
Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:
public class X
{
private int x = 1;
//some other code here
public void setX(int proposedValueForX)
{
if(proposedValueForX != x)
{
doOneTimeTaskIfVariableHasChanged();
x = proposedValueForX;
}
}
}
You can use getter/setter with dirty bit associated with each field. mark it dirty if the value is changed through setter, and force user to use setters
another way is use AOP to intercept changing of fields, AspectJ for example, you could have a look a http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html
Example:
create a variable with the same name with a number.
int var1;
int var2;
if(var1 != var2)
{
//do the code here
var2 = var1;
}
hope this help.
you can also use flag concept, as when ever changing the value of x . assign true for an boolean variable. Keep boolean with default value as false. check by this way.
This way is better than having getters and setters in base of performance, not to have reduntant code of two methods getters and setters.
Assuming you have multiple threads you could create an object monitor and wait for the changed object to wake all blocked threads.
Something like this:
private MyObject myObject;
... other thread ...
while(true) {
myObject.wait()
logic you want to run when notified.
}
... other thread ...
... later on ...
myObject.change();
myObject.notifyAll();
精彩评论