Observer Pattern
Observer Pattern
Monday Tuesday
(Notify) (Notify)
Alarm Alarm
Set Alarm (Subscribe)
Once
Without Observer (Poll)
Notify Subscriber(s)
When the
state changes
to 6:05 AM
Works on Push Model. Observer(s) subscribe to the
Observable object to know about any changes in the state of
the Observable. Once subscribed, the Observer object(s) do
not have to keep polling the Observable object for any
change. Observable pushes the information (notifies) about
the change of state to all Observer(s).
*Please Note that a lot of details on these classes have been omitted for brevity and these
code samples have been provided for showing an idea of how Observer pattern works. In
real Life there would be a lot more details that would be part of these classes and may
need some info to be passed between Observable and Observer.
Observer vs Pub-Sub
In Observer Pattern, both the Observable and the Observer know about
each other (or atleast the Interface / Abstraction of their
implementation) and communicate directly through their interface.