从java9起,java.util.Observer和java.util.observale都被声明为Deprecated.
` * @deprecated
- This class and the {@link Observer} interface have been deprecated.
- The event model supported by {@code Observer} and {@code Observable}
- is quite limited, the order of notifications delivered by
- {@code Observable} is unspecified, and state changes are not in
- one-for-one correspondence with notifications.
- For a richer event model, consider using the
- {@link java.beans} package. For reliable and ordered
- messaging among threads, consider using one of the concurrent data
- structures in the {@link java.util.concurrent} package.
- For reactive streams style programming, see the
- {@link java.util.concurrent.Flow} API.` 原因也列出了,看上面的内容 就是API里的javadoc内容。 Observer和Observable支持的事件模型非常有限,Observable传递的通知顺序未指定,且状态更改与通知不一一对应。对于更丰富的事件模型,请考虑使用java.beans包,为了在线程之间进行可靠且有序的消息传递,请考虑使用java.util.concurrent包中的并发数据结构之一。有关反应式流样式的编程,请参阅java.util.concurrent.Flow API.
问题来了,虽然被标记弃用,但没有指明使用哪些替代接口。
我们可以使用java.beans包中的PropertyChangeEvent和PropertyChangeListener。