Friday, 11 October 2019

Observer Pattern in java

Observer pattern is also refered as Publisher/Subscriber pattern.
Examples:
  • JMS in Java
  • Event listeners like onClick

Applications:
  • When you subscribe to any website
  • Follow feature on Quora/Facebook/Instagram
  • Whatsapp Group

// Subject interface
package example.java.designpatterns;

public interface Subject {
 public void register(Observer observer);
 public void unregister(Observer observer);
 public void notifyObservers();
 public Object getUpdate(Observer observer);
}



// Observer interface

package example.java.designpatterns;

public interface Observer {
 public void update();
 public void setSubject(Subject s);
}




// Class implementing Subject interface
package example.java.designpatterns;

import java.util.ArrayList;
import java.util.List;

public class MyTopic implements Subject {
 private String message;

 private List listeners;

 public MyTopic() {
  listeners = new ArrayList<>();
 }

 public void register(Observer observer) {
  listeners.add(observer);
 }

 public void unregister(Observer observer) {
  listeners.remove(observer);
 }

 public void notifyObservers() {
  for (Observer observer : listeners) {
   observer.update();
  }
 }

 public void pushMessage(String s) {
  System.out.println("MyTopic: Adding message: " + s);
  this.message = s;
  notifyObservers();
 }

 public Object getUpdate(Observer observer) {
  return this.message;
 }
}




// Class implementing Observer interface

package example.java.designpatterns;

public class MyTopicSubscriber implements Observer {
 private Subject topic;
 
 private String name;
 
 public MyTopicSubscriber(String name) {
  this.name = name;
 }
 
 public void update() {
  String message = (String) topic.getUpdate(this);
  System.out.println("MyTopicSubscriber: " + name + " Recieved: " + message);
 }
 public void setSubject(Subject subject) {
  this.topic = subject;
 }
}

No comments:

Post a Comment