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


public class Publisher extends Observable {

public void publishEvent(String eventName) {
//Calling set changed is important for triggering event
//Notify the observers


public class Subscriber implements Observer {

public void update(Observable o, Object 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.publishEvent("Observer Pattern Working");

No comments:

Post a Comment