I am having problms with the observer pattern. It says Observer and Subject should both be interfaces. I see why observers are interfaces, but why isn't it better to have the subject an abstract class? Couldn't you already implement al least remove/register?
The Observer interface isn't perfect, and has been deprecated since Java 9. One of the cons is that Observable isn't an interface, it's a class, and that's why subclasses can't be used as observables. Also, a developer could override some of Observable's synchronized methods and disrupt their thread-safety.
Observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the object that watch on the state of another object are called Observer and the object that is being watched is called Subject.
The main disadvantage of the observer design pattern that subscribers are notified in random order. There is also a memory leakage problem in the observer design pattern because of the observer's explicit register and unregistering.
Consequences. The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or other observers.
Design patterns are meant to be adapted to the particular needs of the applications; they don't prescribe rules set in stone. In particular whether something is an abstract class or an interface is for you to decide, considering all the implications that the decision has for the rest of the application.
That said, interfaces are recommended over abstract classes in general for several reasons. For example abstract classes require you to use inheritance, and in many languages you can't inherit from more than one class. If that's not a problem for your use case, go ahead and use abstract classes if you find them more convenient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With