问题
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);
}
回答1:
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?
回答2:
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");
}
}
来源:https://stackoverflow.com/questions/47614003/observer-pattern-update-parameters