The
observer pattern is a software design pattern in which an object,
called the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.
Lets
take a blog example, where anyone can register and unregister to this
blog. Whenever there is a new post then the registered persons will
be notified.
public interface Subject { void registerObserver(Observer o); void unRegisterObserver(Observer o); void notifyObservers(); }
public interface Observer { void update(); }
import java.util.*; public class MyBlog implements Subject { Set<Observer> mySubscribers = new HashSet<> (); @Override public void registerObserver(Observer o){ mySubscribers.add(o); } @Override public void unRegisterObserver(Observer o){ mySubscribers.remove(o); } @Override public void notifyObservers(){ Iterator<Observer> iter = mySubscribers.iterator(); while(iter.hasNext()){ Observer obs = iter.next(); obs.update(); } } void addPost(){ notifyObservers(); } }
public class Subscribers implements Observer{ String mailId; Subscribers(String mailId){ this.mailId = mailId; } @Override public String toString(){ return mailId; } @Override public void update(){ System.out.println(this + " received notification"); } }
public class ObserverPattern { public static void main(String args[]){ MyBlog learnJava = new MyBlog(); Subscribers s1 = new Subscribers("bcd@bcd.com"); Subscribers s2 = new Subscribers("def@def.com"); Subscribers s3 = new Subscribers("ghi@ghi.com"); learnJava.registerObserver(s1); learnJava.registerObserver(s2); learnJava.registerObserver(s3); learnJava.addPost(); learnJava.unRegisterObserver(s2); learnJava.addPost(); } }
Output
bcd@bcd.com received notification ghi@ghi.com received notification def@def.com received notification bcd@bcd.com received notification ghi@ghi.com received notification
No comments:
Post a Comment