0

Why does the Observer interface has Observable o as a parameter? Do you recommend using Javas existing classes (implements Observer; extends Observable)?

  public class Test implements Observer {
  void update(Observable o, Object arg);
  }

2 Answers2

3

It receives the Observable reference so that the Observer can use it to address the way it will handle the Object arg that was passed. Also, the Observer could call deleteObserver to remove itself once it finished the job.

You shouldn't use them. And it's not me that's telling you, it's the people behind java themselves. Check it out:

https://dzone.com/articles/javas-observer-and-observable-are-deprecated-in-jd https://docs.oracle.com/javase/9/docs/api/java/util/Observable.html

In Java 9, Observer and Observable are deprecated.

Deprecated. This class and the Observer interface have been deprecated. The event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications. For a richer event model, consider using the java.beans package. For reliable and ordered messaging among threads, consider using one of the concurrent data structures in the java.util.concurrent package. For reactive streams style programming, see the Flow API.

Check out this other answer: How observers subscribe on observables?

wleao
  • 2,316
  • 1
  • 18
  • 17
0

If you use this pattern you need both Observer and Observables.


public class Airport extends Observable {

    private final String name;

    public Airport(String name) {
        this.name = name;
    }

    public void planeLanded(String flight) {
        setChanged();
        notifyObservers(flight);
    }

    @Override
    public String toString() {
        return name;
    }
}

public class DispatcherScreen implements Observer {

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Flight " + arg + " landed at " + o.toString());
    }

}

public class Program {

    public static void main(String[] args) {
        Observer screen = new DispatcherScreen();

        Airport airport1 = new Airport("San Francisco International Airport");
        Airport airport2 = new Airport("O'Hare International Airport");
        airport1.addObserver(screen);
        airport2.addObserver(screen);
        //
        airport1.planeLanded("FR1154");
        airport1.planeLanded("UI678");
        airport2.planeLanded("SU1987");
        airport1.planeLanded("UI678");
        airport2.planeLanded("AI4647");
    }

}
LowLevel
  • 1,085
  • 1
  • 13
  • 34
  • 1
    Observer and Observable are deprecated in java9. You shouldn't be using them. Only use them to study the pattern. – wleao Dec 03 '17 at 01:32