Search code examples
javadesign-patternsobserver-pattern

Java reimplement Observer


Why do a lot of people dislike the JDK Observer pattern and suggest to implement your own? Why re-invent the wheel?

The re-implemented observer that I see is same observer of the JDK.


Solution

  • One possible reason is that Observable is a concrete class that you must subclass. Java only has single inheritance, so if you already have a superclass you can't subclass Observable as well.

    A second reason is that you often want to add multiple types of observer (listener) to an object, and Observer doesn't support this directly (you could fire different objects in the notifyObservers method, but that's not as clear as having multiple listener interfaces, and has a lot of potential for error and inefficiency since observers would receive objects not intended for them).