Observer is deprecated in Java 9. What should we use instead of it?

前端 未结 5 1156
再見小時候
再見小時候 2020-11-27 11:24

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

5条回答
  •  死守一世寂寞
    2020-11-27 11:57

    There are more reasons :

    Not Serializable - Since, Observable doesn't implements Serializable. So, you can't Serialize Observable neither its subclass.

    No Thread Safety - The methods can be overridden by its subclasses, and event notification can occur in different orders and possibly on different threads, which is enough to disrupt any "thread safety".

    Less to offer -

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

    Open Issues - As mentioned, there were lot of major issues raised (thread safety, Serializable) and most of them had complexities to fix and still "not fixed" or No Active Development, and that is the reason why it has been deprecated.

    I would also recommend to read this answer Why should the observer pattern be deprecated?, @Jeff has explained other reasons for deprecation.


    So, what's the alternative we have ?

    You can use PropertyChangeEvent and PropertyChangeListener from java.beans package.

提交回复
热议问题