Saturday, 18 June 2016

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
interface Observer{
 void notify(String post);
}
SocialMediaNotifier.java
class SocialMediaNotifier implements Observer{
 @Override
 public void notify(String post) {
  System.out.println("SocialMediaNotifier: New post published :"+post);
 }
}
SubscribedUserNotifier.java
class SubscribedUserNotifier implements Observer{
 @Override
 public void notify(String post) {
  System.out.println("SubscribedUserNotifier: New post published :"+post);
 }
}
Subject.java
interface Subject{
 void addObserver(Observer observer);
 void removeObserver(Observer observer);
 void notifyObservers();
}
JavaByPatelBlogPost.java
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
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.

No comments:

Post a Comment