Sunday, August 17, 2014

Observer Pattern

Observer pattern is similar to publish-subscribe model. The subscriber register themselves with the publishers. When publisher publishes a event, it notifies all the subscriber. Think of it as a subscription done online of for SMS. Whenever any relevant things happen, a SMS or mail is received in the Inbox.

Java in fact provides utility class and interface to implement this pattern. The Observable can be extended from java.util.Observable and the observers can be extended from java.util.Observer. Let's look into a basic example

Observable:

public class Publisher extends Observable {

public void publishEvent(String eventName) {
//Calling set changed is important for triggering event
this.setChanged();
//Notify the observers
this.notifyObservers(eventName);
}
}

Observer:

public class Subscriber implements Observer {

@Override
public void update(Observable o, Object arg) {
System.out.println(arg);
}
}

And the main class

public class ObserverMain {

public static void main(String[] args) {
Publisher publisher = new Publisher();

Subscriber subscriber1 = new Subscriber();
Subscriber subscriber2 = new Subscriber();

publisher.addObserver(subscriber1);
publisher.addObserver(subscriber2);

publisher.publishEvent("Observer Pattern Working");

No comments:

Post a Comment