Observer Design Pattern

Observer Design Pattern.


Observer Design Pattern is used to notify interested Observers on any change to subject.


Observer Design Pattern Example In Java.

In our example we will notify SocialMediaNotifier and SubscribedUserNotifier whenever a new post is published on JavaByPatel blog.  
SocialMediaNotifier and SubscribedUserNotifier will update post to necessary places. 

Observer : SocialMediaNotifier, SubscribedUserNotifier 
Subject : Blog post.


Observer.java
1
2
3
interface Observer{
 void notify(String post);
}
SocialMediaNotifier.java
1
2
3
4
5
6
class SocialMediaNotifier implements Observer{
 @Override
 public void notify(String post) {
  System.out.println("SocialMediaNotifier: New post published :"+post);
 }
}
SubscribedUserNotifier.java
1
2
3
4
5
6
class SubscribedUserNotifier implements Observer{
 @Override
 public void notify(String post) {
  System.out.println("SubscribedUserNotifier: New post published :"+post);
 }
}
Subject.java
1
2
3
4
5
interface Subject{
 void addObserver(Observer observer);
 void removeObserver(Observer observer);
 void notifyObservers();
}
JavaByPatelBlogPost.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class JavaByPatelBlogPost implements Subject{
 private String post;
 private List<Observer> listOfObserver = new ArrayList<Observer>();
  
 @Override
 public void addObserver(Observer observer) {
  listOfObserver.add(observer);
 }
 
 @Override
 public void removeObserver(Observer observer) {
  listOfObserver.remove(observer);
 }
 
 @Override
 public void notifyObservers() {
  for (Observer observer : listOfObserver) {
   observer.notify(post);
  }
 }
  
 public void newPost(String post) {
  this.post = post;
  notifyObservers();
 }
}
ObserverDesignPattern.java
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ObserverDesignPattern {
 
 public static void main(String[] args) {
  SocialMediaNotifier socialMediaNotifier = new SocialMediaNotifier();
  SubscribedUserNotifier subscribedUserNotifier = new SubscribedUserNotifier();
   
  JavaByPatelBlogPost blogPost = new JavaByPatelBlogPost();
  blogPost.addObserver(socialMediaNotifier);
  blogPost.addObserver(subscribedUserNotifier);
   
  blogPost.newPost("HelloPost");
 }
}

You may also like to see


Decorator Design Pattern

Adapter Design Pattern

When to use Builder design pattern

Command Design Pattern

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.