How to create change listener for variable?

Java gives you a simple Observer pattern implementation for this kind of thing, but you’ll need to set your observed variable within a method that manages listener notifications. If you can’t extend Observable, you can either use composition (i.e., have an Observable instance in your class to manage notifications), or you can take a look at java.util.Observable to get an idea of how to roll your own version.

Flux.java

import java.util.Observable;

public class Flux extends Observable {
  private int someVariable = 0;

  public void setSomeVariable(int someVariable) {
    synchronized (this) {
      this.someVariable = someVariable;
    }
    setChanged();
    notifyObservers();
  }

  public synchronized int getSomeVariable() {
    return someVariable;
  }
}

Heraclitus.java

import java.util.Observable;
import java.util.Observer;

public class Heraclitus implements Observer {
  public void observe(Observable o) {
    o.addObserver(this);
  }

  @Override
  public void update(Observable o, Object arg) {
    int someVariable = ((Flux) o).getSomeVariable();
    System.out.println("All is flux!  Some variable is now " + someVariable);
  }
}

Leave a Comment