Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer Pattern abstract vs interface

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?

like image 653
Maximosaic Avatar asked Jun 05 '13 19:06

Maximosaic


People also ask

Is Observer an interface?

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.

When should the Observer pattern be used?

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.

What is the disadvantage of Observer design pattern?

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.

What are the two consequences of using the Observer pattern?

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.


1 Answers

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.

like image 127
Joni Avatar answered Nov 16 '22 22:11

Joni