How to detect if a variable has changed?

前端 未结 6 1349
生来不讨喜
生来不讨喜 2020-12-10 06:16

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;
in         


        
相关标签:
6条回答
  • 2020-12-10 06:25

    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

    0 讨论(0)
  • 2020-12-10 06:30

    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.

    0 讨论(0)
  • 2020-12-10 06:34

    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

    0 讨论(0)
  • 2020-12-10 06:42

    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();
    
    0 讨论(0)
  • 2020-12-10 06:47

    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.

    0 讨论(0)
  • 2020-12-10 06:50

    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;
           }
        }
    }
    
    0 讨论(0)
提交回复
热议问题