I'm studying design patterns from a course at coursera. They have there course notes in which they define the Subject
of the observer design pattern as super class as shown in the image and code below
Now I think the Subject
class is useless by itself until a subclass inherit from it and make any specific subject. In that case shouldn't the Subject
be a java interface
instead ? What is the reason that the Subject
is not a java interface but the Observer
is.
Is there any specific reason for that. I'm a little confused about this.
Thanks
If Subject
was an interface, then every class that implements Subject
must re-implement all the registerObserver
, unregisterObserver
, and notify
methods which are very standard.
You may say that you will put those methods into a helper class so that every derived Subject
can just delegate the tasks to this helper. But after all, you have to duplicate the delegation code for all derived Subject
classes. Althought the delegation code is short and straight-forward, that duplication is still frustrating.
You can find that argument near the end of this very interesting article of Uncle Bob: http://blog.cleancoder.com/uncle-bob/2015/01/08/InterfaceConsideredHarmful.html
Observer DP is a simple.
The Subject is the entity that the Observer watches.
The Subject is single entity and the Observers can be more than one.
The Subject has the List observers, but the Observer will have the Subject.
Any change in the Subject will be notified to all the observers that the Subject stores in the form of a list.
We can have the Subject as interface too. All depends on way we implement the above points.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.