Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a class as Observable and Observer both

technically it seems OK to define a Class as both Observable and Observer using the following code:

public class Data extends Observable implements Observer

however, trying to implement it, it's not working.

public class Data extends Observable implements Observer {

    @Override
    public void update(Observable o, Object o1) {
        System.out.println("SC");        
    }

    Integer A;
    String B;
    Float C;

    public Data() {
        this.addObserver(this);
    }

    public void setA(Integer A) {
        this.A = A;
        notifyObservers();
    }

    public void setB(String B) {
        this.B = B;
        notifyObservers();
    }

    public void setC(Float C) {
        this.C = C;
        notifyObservers(this.C);
    }

}

with the main function as below:

public static void main(String[] args) {
    Data d = new Data();
    d.setA(5);
    d.setB("Hi");
    d.setC(2.0f);
}

it should prints some "SC" but it's not working. Can anyone describes why?

like image 791
MBZ Avatar asked Oct 17 '12 11:10

MBZ


People also ask

What are the observer and observable classes?

The Java language supports the MVC architecture with two classes: Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.

Is Observer a class or interface?

An observer is a class or structure that implements the IObserver<T> interface. The observer must implement three methods, all of which are called by the provider: IObserver<T>.

What is an observable class?

Observable is a class in the Java programming language that allows you to construct subclasses that other sections of the program can observe. Observing classes are informed when an object of this subclass changes.


1 Answers

If you don't .setChanged(), then .notifyObservers() has no effect. This is the case both if you have separate classes defining Observable and Observers, or if you have a single class, as in your example.

Try changing your setters as follows:

public void setC(Float C) {
  this.C = C;
  setChanged();  // <-- add this line
  notifyObservers(this.C);
}

From the documentation of Observable,

setChanged() Marks this Observable object as having been changed; the hasChanged method will now return true.

notifyObservers(Object arg) If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

like image 177
Bruno Reis Avatar answered Sep 18 '22 22:09

Bruno Reis