java 如何在每次变量改变时调用函数?

omhiaaxx  于 2022-11-27  发布在  Java
关注(0)|答案(3)|浏览(185)

我正在寻找一种方法,使一个函数(如更新函数)被调用,每次一个特定的变量以某种方式改变。无论是由我或其他,在调用未知函数。
这可能吗?如果可能,我该怎么做?

snvhrwxg

snvhrwxg1#

不幸的是,没有直接的方法来实现这一点。但是一个可以接受的解决方案是使用setter:

private int a = 1;

public void setA(int a) {
    this.a = a;
    update();
}

public static void main(String[] args) {
    Main m = new Main();
    m.setA(2);
}
wnvonmuf

wnvonmuf2#

最灵活方法是使用PropertyChangeSupport并编写如下内容:

import java.beans.PropertyChangeSupport;

public class MyClass {
    private PropertyChangeSupport pptChangeSupport;

    private int field1;
    private int field2;
    private int field3;

    public int getField1() {
        return field1;
    }

    public void setField1(int field1) {
        int oldValue = this.field1;
        this.field1 = field1;
        fireChange("field1", oldValue, field1);
    }

    public int getField2() {
        return field2;
    }

    public void setField2(int field2) {
        int oldValue = this.field2;
        this.field2 = field2;
        fireChange("field2", oldValue, field2);
    }

    public int getField3() {
        return field3;
    }

    public void setField3(int field3) {
        int oldValue = this.field3;
        this.field3 = field3;
        fireChange("field3", oldValue, field3);
    }

    public MyClass() {
        // TODO Auto-generated constructor stub
    }

    private void fireChange(String pptName, int oldValue, int newValue) {
        if (pptChangeSupport != null) {
            getPropertyChangeSupport().firePropertyChange(pptName, oldValue, newValue);
        }
    }

    private PropertyChangeSupport getPropertyChangeSupport() {
        return pptChangeSupport == null ? pptChangeSupport = new PropertyChangeSupport(this) : pptChangeSupport;
    }

    public static void main(String[] args) {
        MyClass object = new MyClass();
        PropertyChangeSupport pptchangesupport = object.getPropertyChangeSupport();
        pptchangesupport.addPropertyChangeListener(e -> System.out
                .println("property " + e.getPropertyName() + " changed : " + e.getOldValue() + " -> " + e.getNewValue()));
        object.setField1((int) (Math.random()*Integer.MAX_VALUE));
        object.setField3((int) (Math.random()*Integer.MAX_VALUE));
        object.setField2((int) (Math.random()*Integer.MAX_VALUE));
        object.setField1((int) (Math.random()*Integer.MAX_VALUE));
        object.setField2((int) (Math.random()*Integer.MAX_VALUE));
        object.setField3((int) (Math.random()*Integer.MAX_VALUE));
        object.setField2((int) (Math.random()*Integer.MAX_VALUE));
    }


}
zbdgwd5y

zbdgwd5y3#

除了在设置变量后自己调用update之外,还可以将其封装在函数调用中,并确保所有a =用法都使用setA
否则,没有用于重新分配变量的“通知系统

private static void setA(int a) { 
    Main.a = a;
    update();
} 

public static void main(String[] args){
    setA(2);
}

除了这个简单的例子之外,您所寻找的就是Observer设计模式

相关问题