问题描述
Java 9问世了,已被弃用。
为什么?这是否意味着我们不应该再实施观察者模式了?
Java 9 came out, and Observer
has been deprecated.Why is that? Does it mean that we shouldn't implement observer pattern anymore?
知道什么是更好的选择会很好吗?
It would be good to know what is a better alternative?
推荐答案
为什么?这是否意味着我们不应再实施观察者模式了?
首先回答后一部分 -
Answering the latter part first -
是 ,这确实意味着您不应该实施 Observer
和 Obervable
s。
很好地预先提出 Observer
有一个弱点:所有可观察的
是相同的。您必须实现基于 instanceof
的逻辑,并将对象转换为具体类型为 Observable.update()
方法。
Alex's answer puts it nicely upfront that Observer
has a weakness: all Observable
s are the same. You have to implement the logic that is based on instanceof
and cast object to concrete type into Observable.update()
method.
要添加它,有一个像类,因为它没有实现 Serializable
界面和所有其成员是私人的。
To add to it there were bugs like one could not serialize the Observable
class because as it didn't implement Serializable
interface and all of its members were private.
有什么更好的替代方案?
另一方面监听器
有很多类型,他们有回调方法,不需要强制转换。正如@Ravi在其中指出的那样,您可以使用。
On the other hand Listeners
have a lot of types and they have callback methods and doesn't require casting. As pointed by @Ravi in his answer you can make use of PropertyChangeListener
instead.
对于其余部分, @Deprecation
已经标记了适当的文档,以探索其他链接在其他包中答案也是如此。
For the rest of it the @Deprecation
has been marked with proper documentation to explore other packages as linked in other answers as well.
请注意,弃用也标有分析,如 -
Note that the deprecation was also marked with an analysis as stated in this mail -
编辑 :还值得一提的是,API的弃用主要不仅仅是因为上述原因,而且还无法维护一些错误报告的评论中提到的遗留代码(上面链接) )这是为了在一种或另一种方式上改进其实施而提出的。
Edit: Its also worth mentioning that the deprecation of the APIs is not primarily just because of the above reason but also being unable to maintain such legacy code as mentioned in comments of few of the bug reports(linked above) which were raised to mark an improvement in its implementaion in one or the other way.
这篇关于在Java 9中不推荐使用Observer。我们应该使用什么而不是它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!