0% found this document useful (0 votes)
12 views

Observer Pattern

Uploaded by

fshah000000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Observer Pattern

Uploaded by

fshah000000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Observer Pattern

Monday Tuesday
(Notify) (Notify)
Alarm Alarm
Set Alarm (Subscribe)
Once
Without Observer (Poll)

Is it 6:00 am yet? Is it 6:00 am yet? Is it 6:00 am yet?


Used to notify about the “change in state” of an object to all
the subscriber objects. There can be one or more subscribers.

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).

Observable object keeps list of all the subscribers.

An example of “Dependency Inversion Principle”.

Events (Button Click) are the most common example of


Observer Pattern.
Some more examples of Observer Pattern

Youtube Notifications of new content added on


subscribed channel

New Email from a subscribed newsletter.

Notification about a product getting added to the


inventory which was earlier Not available.

When HR Team “really” gets back to you.


Creating Interfaces
Lets try to replicate the Youtube like Subscription and notification
Creating Observable (Channel)
Creating Observer (User)
Subscription and Notification

*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

Pub-Sub Model is pretty similar to Observer model with some


differences in implementation and usage.

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.

However, In the Publisher Subscriber Pattern, these publishers and


subscribers don’t have any knowledge about each other and they
communicate via an external medium, for example a Message Broker or
an Event Bus like RabbitMQ or MassTransit
Let us know where have you used Observer Pattern in your
applications. Repost this, if you liked it. Please follow Amritpal
Singh for more similar articles and posts.

You might also like