Why do I need an Observer pattern?

I read a book about the observer pattern. He gives the following example:

Class clockusing methodtime()

The class messagethat inherits from it 3 classes: Fax, Mail, Memo.

The app wants to send a message when 12AM arrives.

The book recommends the observer pattern. It says that if we add a new class: VideoMsgthat extends the message, this will affect the implementation of the Clock class. But I did not understand why. The Clock class will contain a collection of the object message, and if we add a new inherit class, it will not change the clock class.

I would appreciate if someone would explain the above example or give a better example.

+3
source share
5

,

1000 .

, , .

, .

+3

, , subscribe , 12AM, notifyObservers, notify, , 12AM.

-, - , .

+1

, , .

Observer "Observed object" (Subject) Observers, Subject "" . , , , , .

. , , , , .

0

:

, , .

Observer OO Inheritance Polymorphism, , FLEXIBLE .

0

Besides the missing details, I would suggest that the “messages” watch the clock to run the “actions” on time. Depending on how (watching)? it is implemented, it can mean a change of hours. The observer pattern is "we call you - do not call us." This basically prevents the expensive waiting cycle.

0
source

All Articles