Hello folks,

This post is all about to the Observer Design pattern.

There is common occurring problem where we need to define ” a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically “.

Everyday we subscribe the NewsLetter to get update emails. This is very much similar to as above said where NewsLetter status changes when new message added to NewsLetter, then all its subscribers should gets notified.

Observer Design pattern has 3 actors A Subject, an Observer and Observable objects.It is also called publisher-Subscriber Pattern.

Lets take this use case and try to implement Observer Design pattern..

Message object which is going to change an state of NewsLetter Object by simply adding to NewsLetter.

Message Type.

 NewsLetter as Subject class.

We have List of Observers which are gets notified when NewsLetter object changes state (add an message to NewsLetter Object).Lets say we have only EmailObserver is Observer now added.

 Observer interface as Observer

EmailObserver interface Implemention class

In his class We have update method which will gets called when NewsLetter object changes state. I have added some println lines to display but these can be replaced with actual logic for sending an email.

This EmailObserver has also 2 methods for subscribing and unsubscribing an email from NewsLetter.These methods add or remove given email from subscription list.

Lets test it.

At any time you can test this by adding or removing Observer from NewsLetter Observers list.
If you want to add new Observer,It is very simple.
Create new Observer.

And Add this Observer to Subject Observers list nothing but add this Observer to NewsLetter observers list.

Form now onwards both Observers will gets notified when State of NewsLetter has been changed.
At any time you can get rid off from notifcation by removing corresponding observer.

Hope This worked for you.