如何检测变量是否已更改?

Amp*_*y91 8 java

我发现自己只想在变量发生变化时才想在程序中做某些事情.到目前为止,我一直在做这样的事情:

int x = 1;
int initialx = x;

...//code that may or may not change the value of x

if (x!=initialx){
    doOneTimeTaskIfVariableHasChanged();
    initialx = x; //reset initialx for future change tests
}  
Run Code Online (Sandbox Code Playgroud)

这样做有更好/更简单的方法吗?

jam*_*ond 6

由于您只想在值发生变化时查找并执行某些操作,我会使用setXXX,例如:

public class X
{
    private int x = 1;

    //some other code here

    public void setX(int proposedValueForX)
    {
       if(proposedValueForX != x)
       {
           doOneTimeTaskIfVariableHasChanged();
           x = proposedValueForX;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)