1

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.

2
  • Where do you see reimplementations? Commented Feb 22, 2012 at 10:13
  • In a lot of question on SO, the folks suggest to implement your Observer instead the one in the JDK.. Commented Feb 23, 2012 at 20:12

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

5 Comments

I understand the problem of listeners, but I don't understand very well why subclassing Observable is a problem...Can you post me an example?
So in this case, in your class that you want to observe, you implements some Observers? Like "implements observer1, observer2, ecc". Right?
implements is for interfaces - but Observable is a class, not an interface (my previous comment should say Observable instead of Observer, sorry - I will delete it and re-post it below as it's too confusing otherwise).
There are lots of situations where I would want to observe a class that already has a superclass e.g. because the superclass holds functionality that is common to multiple subclasses. But I can't do this by subclassing Observable, because my class already has a superclass - Java only allows a single superclass.
I used Observable as interface for a while. Then when I see that I must reimplement addOb() - delOb() - notifyOb() for each class, I prefer use an abstract class that have already implemented that methods.
1

java.util.Observable is a class. not an interface As such it provides some functionality without you having to code it yourself, but it means that your own class which extends it, cannot extend any other class. This is a limitation.

Other patterns have Observable as an interface and do not have that issue (but have the cost of you having to implement some more code yourself)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.