It is the most popular design pattern. It comes under the behavioral pattern category.

Publishers + Subscribers = Observer Pattern

  1. Publisher: Who publishes something.

Let us understand by taking a real-life example of YouTube. Today everyone uses YouTube. So, I think it will be the best example to explain.

In YouTube, if any YouTuber uploads a video, then all subscribers of that YouTuber will get an instant notification. So here Youtuber is Publisher and Subscriber is of course subscriber.

Let’s see the implementations:

We will be having two Interface Channel and Observer.

Then we will be having a YouTuber class that will implement Channel Interface.

As you can see that we are having one more method uploadVideo in the YouTuber class, Whenever a YouTuber will upload a video, we need to notify every subscriber. So as you can see in line 33 we have called notifySubscribers method.

Here is my Subscriber class that implements Observer. In the Subscriber class, we are having two more methods to subscribe and unsubscribe to a channel.

Now, it's time to add driver class names as YouTube.

So, we will be creating a YouTuber class object and create the object of every subscriber. As you can see in line 7, hunny is subscribing to YouTuber. Hence only hunny will get notified when a video will get uploads in line 8. And similarly, when line 11 will get executed, every subscriber will get the notification as you can see in the output below.

Observer Pattern

Although we have broken some solid principles here, my intent was just to explain the Observer pattern.

If you are able to identify those broken principles, don’t forget to share them in the comment section.

If you like this article, you can click on the clap button to appreciate me and share it with your friends, if you didn’t like this, unfortunately, we don’t have a dislike button here. If you have any thoughts to share, you can share in the comment section or you can inbox me at hunnychawla528@gmail.com.

Application Developer