Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Observer pattern


Published on

This note shows how we can use Observer Pattern in Java

Published in: Software
  • Be the first to comment

  • Be the first to like this

Observer pattern

  1. 1. Observer Pattern in Java by Somenath Mukhopadhyay som-itsolutions
  2. 2. As i was going through the different source code files of the Java Util package, i found the implementation of the Observer Pattern ( see the Gang of Four book for more information on this pattern) in the two places - namely and i would like to throw some lights on these two classes. These two classes can be found in the Javaj2sesrcshareclassesjavautil folder of the JDK source code. But first of all, i need to give you a practical example of why we need observer pattern in the first place. Suppose, we have a document which can be viewed simultaneously by three different views – say one view represnts a line graph chart, another view represents it in a spreadsheet, yet another view represnts a pie chart. Now suppose the spreadsheet view makes some modification to the document. If the other two views don't update themselves with this changed state of the document, different views will be in inconsistent states. So we need some mechanism to notify the other two views whenever the spreadsheet view updates the document. This is done through Observer pattern in which whenever the document changes stete, it notifies all of its views. The views in turn updates themselves with the latest data. Fig 1: Class Diagram of Observer Pattern
  3. 3. Fig 2: Sequence Diagram of Observer Pattern What these two diagrams essentially depict is that in the Observer Pattern, we have a Subject, which can attach one or more Observers through its Attach() function. Whenever it changes its state it Notifies all the attached Observers through its notify function. The observers in turn synchronize their states with that of the Subject through the GetSubjectState function. So now let us first start with the class. As the name suggests it is the class which will implemented functionalities for being observed. Or in other words it is the class which helps in designing the Subject class of the Observer pattern discussion of the GoF book. We need to extend this class to get the Subject class. Let us try to dissect this class. The following functions are there in this class: 1. Data Members : It has a vector to hold all the observers that are interested in observing this observable class. It has another boolean data member called "changed" to indicate if anything has changed in the Subject class ( which will be derived from this Observable class). 2. Constructor : This class has a no argument constructor to construct an empty vector of Observers.
  4. 4. 3. Member Functions :  addObserver : To add an observer to its list of Observers.  deleteObserver : To delete a particular observer from the list of the observers  notifyObservers : There are two overloaded versions of this function. One takes an Object parameter as an argument and the other does not take any argument. The task of this function is to notify all the attached observers when any data of the subject gets changed. To check whether the data is changed it evaluates the boolean "changed" data member. This function also calls the update function of each observer objects to ask them to get in sync with the subject's changed state. The overloaded version that takes an one argument parameter is used to let the observers know about which attribute is changed. And the other version of this function which does not take any argument does not let the observer know about which attribute is changed.  deleteObservers : This function removes all the observers attached to this subject.  setChanged : This function sets the boolean data member "changed".  clearChanged : This function resets the boolean data member "changed".  hasChanged : This function helps us to know whether the data of the subject has been changed or not.  countObservers : This function returns the number of observers attached to this subject. This is all about the Observable class which helps us to define to Subject class.
  5. 5. The defines an interface called Observer having just one abstract function called update (Observable o, Object arg). As the name suggests, the Observer class that will implement this interface will override the update function to set the attribute passed as an argument (arg) from the Subject class. This method is called whenever any attribute in the Subject class gets changed. Now let us try to see an example to understand how this Observer Pattern is used. Let us first extend the Observable class to create the Subject class. package; import java.util.Observable; public class Subject extends Observable { private String name; private float price; public Subject(String name, float price) { = name; this.price = price; } public String getName() { return name; } public float getPrice() { return price; } public void setName(String name) { = name; setChanged(); notifyObservers(name); } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); } } As this is clear from the implementation of the Subject class, that whenever we call the setter function to change the attributes of the Subject's object, we call the notifyObservers and pass that attribute as a parameter. Now let us see how we create two different observers namely NameObserver and PriceObserver to observe these two attributes of the Subject class.
  6. 6. // An observer of name changes. package; import java.util.Observable; import java.util.Observer; public class NameObserver implements Observer { private String name; public NameObserver() { name = null; System.out.println("NameObserver created: Name is " + name); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub if (arg instanceof String) { name = (String)arg; System.out.println("NameObserver: Name changed to " + name); } } }
  7. 7. // An observer of price changes. package; import java.util.Observable; import java.util.Observer; public class PriceObserver implements Observer { private float price; public PriceObserver() { price = 0; System.out.println("PriceObserver created: Price is " + price); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub if (arg instanceof Float) { price = ((Float)arg).floatValue(); System.out.println("PriceObserver: Price changed to " + price); } } } As it has become clear from the above two implementations that the update function actually helps in synchronizing the state of the concrete observers with that of the Subject. Now the client of the Observer framework will look like the following :
  8. 8. package; public class Main { public static void main(String args[]) { // Create the Subject and Observers. Subject s = new Subject("Kheer Kadam", 20.5f); NameObserver nameObs = new NameObserver(); PriceObserver priceObs = new PriceObserver(); // Add those Observers! s.addObserver(nameObs); s.addObserver(priceObs); //Initial Subject States System.out.println("Initial states of Subject"); System.out.println("Name : " + s.getName()); System.out.println("Price : " + Float.toString(s.getPrice())); // Make changes to the Subject. s.setName("Gulabjamun"); // It prints NameObserver: Name changed to Gulabjamun s.setPrice(15.0f); //It prints PriceObserver: Price changed to 15.0 s.setPrice(30.5f); //It prints PriceObserver: Price changed to 30.5 s.setName("Rasgulla"); // It prints NameObserver: Name changed to Rasgulla } } Hope the above discussion will help people understand of how the Java supports implementing the Observer pattern.