observer java,在Java 9中不推荐使用Observer。我们应该使用什么而不是它?

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?

解决方案

Why is that? Does it mean that we shouldn't implement observer pattern anymore?

Answering the latter part first -

YES, it does mean you shouldn't implement Observer and Obervables anymore.

They didn't provide a rich enough event model for applications. For example, they could support only the notion that something has changed, but didn't convey any information about what has changed.

Alex's answer puts it nicely upfront that Observer has a weakness: all Observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.

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.

What is a better alternative to that?

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.

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 -

These days, anyone encountering these is probably hitting them by

mistake while using RxJava or other reactive-stream frameworks. In

which case, users will normally want to instead use the jdk9

java.util.concurrent.Flow APIs that all reactive-streams frameworks

should be compatible/interoperable within their planned upcoming

jdk9-compatible versions.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值