M. S. Ramaiah School of Advanced Studies 
1 
CSN2504 Principles of Programming Presentation 
Observer design pattern 
Anshuman Biswal 
PT 2012 Batch, Reg. No.: CJB0412001 
M. Sc. (Engg.) in Computer Science and Networking 
Module Leader: Dr. PVR Murthy Module Name: Principles of Programming Module Code : CSN2504
M. S. Ramaiah School of Advanced Studies 
2 
Marking 
Head 
Maximum 
Score 
Technical Content 
05 
Grasp and Understanding 
05 
Delivery – Technical and General Aspects 
05 
Handling Questions 
05 
Total 
20
M. S. Ramaiah School of Advanced Studies 
3 
Presentation Outline 
•Introduction 
•A sample app: Weather monitoring system 
•First misguided step of development 
•What is wrong in the implementation 
•Example of observer pattern 
•What is observer pattern 
•The concept behind Observer pattern 
•Observer pattern- class diagram 
•Weather app implementation using Observer pattern 
•Weather app implementation using java api of Observer patternn 
•Conclusion 
•References
M. S. Ramaiah School of Advanced Studies 
4 
Introduction- Pattern 
What? 
•Current use comes from the work of the architect Christopher Alexander 
•Alexander studied ways to improve the process of designing buildings and urban areas 
•“Each pattern is a three-part rule, which expresses a relation between a certain context, a problem and a solution.” 
•Hence, the common definition of a pattern: “A solution to a problem in a context.” 
•Patterns can be applied to many different areas , including software development. 
Why patterns in Software Development? 
•"Designing object-oriented software is hard and designing reusable object-oriented software is even harder." - Erich Gamma 
•Experienced designers reuse solutions that have worked in the past 
•Well-structured object-oriented systems have recurring patterns of classes and objects 
•Knowledge of the patterns that have worked in the past allows a designer to be more productive and the resulting designs to be more flexible and reusable 
History: 
•1987 - Cunningham and Beck used Alexander’s ideas to develop a small pattern language for Smalltalk 
•1990 - The Gang of Four (Gamma, Helm, Johnson and Vlissides) begin work compiling a catalog of design patterns 
•1991 - Bruce Anderson gives first Patterns Workshop at OOPSLA(Object Oriented Programming, Systems, Languages and Applications) 
•1993 - Kent Beck and Grady Booch sponsor the first meeting of what is now known as the Hillside Group 
•1994 - First Pattern Languages of Programs (PLoP) conference 
•1995 - The Gang of Four (GoF) publish the Design Patterns book
M. S. Ramaiah School of Advanced Studies 
5 
A sample application: Weather monitoring system 
•The application provides three display elements : current condition, weather statistics and a simple forecast, all updated in real time as the WeatherData object acquires the most recent measurements. Also there is a need of expansion of display system in future.The job is to create an app that uses the Weather data object to update three displays for current conditions, weather stats, and a forecast. The job is to create an app that uses the WeatherData object to show the three displays for current conditions, weather stats, and a forecast. 
Weather station 
Weather Data Object 
Display Device 
Humidity sensor device 
Temperature sensor device 
Pressure sensor device 
Pulls data 
displays
M. S. Ramaiah School of Advanced Studies 6 
A sample application: Weather monitoring system 
• The WeatherData file 
WeatherData 
+getTemperature() 
+getHumidity() 
+getPressure() 
+measurementChanged() 
These three methods return the most recent 
weather measurements for 
temperature,humidity and barometric pressure 
This is called when the weather measurements 
are updated 
Our task is to implement measurementChanged() so that it updates the three displays for 
current condition, weather stats and forecast. Also the system must be expandable i.e. other 
developers can add any other display elements and users can add or remove any display 
element as they want to the application
M. S. Ramaiah School of Advanced Studies 
7 
First misguided step of development 
public class WeatherData{ 
//instance variable declarations 
public void measurementChanged(){ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
currentConditionDisplay.update(temp,humidity,pressure); 
statisticsDisplay.update(temp,humidity,pressure); 
forecastDisplay.update(temp,humidity,pressure); 
} 
} 
//other weather data methods here 
}
M. S. Ramaiah School of Advanced Studies 
8 
What is wrong in the implementation ? 
public class WeatherData{ 
//instance variable declarations 
public void measurementChanged(){ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
currentConditionDisplay.update(temp,humidity,pressure); 
statisticsDisplay.update(temp,humidity,pressure); 
forecastDisplay.update(temp,humidity,pressure); 
} 
} 
//other weather data methods here 
} 
We need to encapsulate these
M. S. Ramaiah School of Advanced Studies 
9 
What is wrong in the implementation ? 
public class WeatherData{ 
//instance variable declarations 
public void measurementChanged(){ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
currentConditionDisplay.update(temp,humidity,pressure); 
statisticsDisplay.update(temp,humidity,pressure); 
forecastDisplay.update(temp,humidity,pressure); 
} 
} 
//other weather data methods here 
} 
We need to encapsulate these 
We can have a common interface to talk to the display elements …they all have the update() that will take temp,humidity and pressure values
M. S. Ramaiah School of Advanced Studies 
10 
What is wrong in the implementation ? 
public class WeatherData{ 
//instance variable declarations 
public void measurementChanged(){ 
float temp = getTemperature(); 
float humidity = getHumidity(); 
float pressure = getPressure(); 
currentConditionDisplay.update(temp,humidity,pressure); 
statisticsDisplay.update(temp,humidity,pressure); 
forecastDisplay.update(temp,humidity,pressure); 
} 
} 
//other weather data methods here 
} 
We need to encapsulate these 
We can have a common interface to talk to the display elements …they all have the update() that will take temp,humidity and pressure values 
By coding to concrete implementation we have no way to add or remove other display elements without making changes to the program
M. S. Ramaiah School of Advanced Studies 
11 
Example of Observer pattern 
•Example: newspaper and magazine subscription 
•Newspaper publisher goes into business and publishes newspaper 
•User subscribe to the subscription and everytime there is any new edition it is delivered to the user. 
•User unsubscribe if they don’t want,then the news paper stops getting delivered to you. 
•Simillairly many users keep of subscribing and unsubscribing the news paper.
M. S. Ramaiah School of Advanced Studies 
12 
Observer pattern 
•Publisher + Subscribers = observer pattern 
•In observer pattern publisher is called the subject and subscriber is called the observer 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects 
Not an Observer
M. S. Ramaiah School of Advanced Studies 
13 
Observer pattern 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects
M. S. Ramaiah School of Advanced Studies 
14 
Observer Pattern 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects
M. S. Ramaiah School of Advanced Studies 
15 
Observer pattern 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects
M. S. Ramaiah School of Advanced Studies 
16 
Observer pattern 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects 
Not an Observer object
M. S. Ramaiah School of Advanced Studies 
17 
Observer pattern 
•Defines a one to many dependency between objects so that when one object changes state,all its dependents are notified and updated. 
Times Of India 
Subject 
Varun 
Naveen 
Sujeet 
Observer objects 
Dependent objects 
Automatic update notification 
Object that holds state 
One to many relation
M. S. Ramaiah School of Advanced Studies 18 
Observer pattern : Class diagram 
Subject 
<<Interface>> 
+registerObserver() 
+removeObserver() 
+notifyObserver() 
Observer 
<<Interface>> 
+update() 
observers 
ConcreteSubject 
+registerObserver() 
+removeObserver() 
+notifyObserver() 
+getState() 
+setState() 
ConcreteObserver 
+update() 
+...() 
+//other observer specific methods() 
Subject 
This is the subject interface.Objects use 
this to register as observer and also to 
remove themselves from being observers 
Each subject can have many observers 
All observers need to implement 
the observer interface. The 
update() gets called when the 
Subject’s state changes 
Concrete observer 
can be any class that 
implements the 
Observer 
interface.Each 
Observer registers 
with concrete subject 
to receive updates 
A concrete Subject 
always implements 
the Subject 
interface.In addition 
to register and 
remove methods the 
concrete subject 
implements the 
notifyObserver 
method that is used 
to update all current 
observers whenever 
the state changes
M. S. Ramaiah School of Advanced Studies 19 
Designing the Weather application 
Subject 
<<Interface>> 
+registerObserver() 
+removeObserver() 
+notifyObservers() 
Observer 
<<Interface>> 
+update() 
WeatherData 
+registerObserver() 
+removeObserver() 
+notifyObservers() 
+getTemperature() 
+getHumidity() 
+getPressure() 
+measurementsChanged() 
CurrentConditions 
+update() 
+display() 
StatisticsDisplay 
+update() 
+display() 
ForecastDisplay 
+update() 
+display() 
DisplayElement 
<<Interface>> 
+display() 
ThirdPartyDisplay 
+update() 
+display() 
Observers 
Subject 
All Obeserver Components implement the 
Observer interface.This gives the subject a 
common interface to 
talk to when it comes time to update 
Display interface for display elements 
to implement the Display interface 
Developers can implement 
the Display and the 
Observer interface 
to create their own Display 
element 
This display element shows 
The current condition of the 
Weather data 
This display element keeps track 
Of min/max/avg measurements 
and display them 
This display shows the 
Weather forecast based on barometer 
Weather data implements the 
Subject interface 
This is the subject interface
M. S. Ramaiah School of Advanced Studies 20 
Designing the Weather application 
Subject 
<<Interface>> 
+registerObserver() 
+removeObserver() 
+notifyObservers() 
Observer 
<<Interface>> 
+update() 
WeatherData 
+registerObserver() 
+removeObserver() 
+notifyObservers() 
+getTemperature() 
+getHumidity() 
+getPressure() 
+measurementsChanged() 
CurrentConditions 
+update() 
+display() 
StatisticsDisplay 
+update() 
+display() 
ForecastDisplay 
+update() 
+display() 
DisplayElement 
<<Interface>> 
+display() 
ThirdPartyDisplay 
+update() 
+display() 
Observers 
Subject 
These display elements should have a pointer 
To the WeatherData labelled “subject”
M. S. Ramaiah School of Advanced Studies 
21 
Weather App implementation 
public interface Subject { 
public void registerObserver(Observer o); 
public void removeObserver(Observer o); 
public void notifyObservers(); 
} 
public interface Observer { 
public void update(float temp,float humidity,float pressure); 
} 
public interface DisplayElement { 
public void display(); 
}
M. S. Ramaiah School of Advanced Studies 
22 
Implementing subject interface in Weather Data 
public class WeatherData implements Subject { 
private ArrayList observers; 
private float temp,humidity,pressure; 
public WeatherData(){ 
observers = new ArrayList(); 
} 
@Override 
public void registerObserver(Observer o) { 
observers.add(o); 
} 
@Override 
public void removeObserver(Observer o) { 
int i = observers.indexOf(o); 
if(i>=0){ 
observers.remove(i); 
} 
}
M. S. Ramaiah School of Advanced Studies 
23 
@Override 
public void notifyObservers() { 
for(int i = 0;i< observers.size();i++){ 
Observer observer = (Observer)observers.get(i); 
observer.update(temp,humidity,pressure); 
} 
} 
public void measurementChanged(){ 
notifyObservers(); 
} 
public void setMeasurement(float temperature,float humidity,float pressure){ 
temp = temperature; 
this.humidity = humidity; 
this.pressure = pressure; 
measurementChanged(); 
} 
} 
Implementing subject interface in Weather Data
M. S. Ramaiah School of Advanced Studies 
24 
Build the display elements 
public class CurrentConditionDisplay implements Observer, DisplayElement { 
private float temperature,humidity; 
private Subject weatherData; 
public CurrentConditionDisplay(Subject weatherData){ 
this.weatherData = weatherData; 
weatherData.registerObserver(this); 
} 
@Override 
public void display() { 
System.out.println("Current Conditions:"+temperature +" F degrees and "+humidity+" % humidity ."); 
} 
@Override 
public void update(float temp, float humidity, float pressure) { 
this.temperature = temp; 
this.humidity = humidity; 
display(); 
} 
}
M. S. Ramaiah School of Advanced Studies 
25 
Lets use the Weather app 
public class WeatherStation { 
public static void main(String[] args) { 
WeatherData weatherData = new WeatherData(); 
CurrentConditionDisplay currentDisplay = new CurrentConditionDisplay(weatherData); 
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 
weatherData.setMeasurement(80.0f, 65.0f, 30.4f); 
weatherData.setMeasurement(82.0f, 70.0f, 29.2f); 
weatherData.setMeasurement(78.0f, 90.0f, 29.2f); 
} 
}
M. S. Ramaiah School of Advanced Studies 
26 
Addition of HeatIndex display 
New requirement to provide the display element of Heat index where Heat index = 
((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) + (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +(0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +(0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) +0.000000000843296 * (t * t * rh * rh * rh)) -(0.0000000000481975 * (t * t * t * rh * rh * rh))) where T is the temperature and RH is the relative humidity 
So just create a HeatIndexDisplay element 
public class HeatIndexDisplay implements DisplayElement, Observer { 
float heatIndex = 0.0f; 
private WeatherData weatherData; 
public HeatIndexDisplay(WeatherData weatherData) { 
this.weatherData = weatherData; 
weatherData.registerObserver(this); 
} 
public void update(float t, float rh, float pressure) { 
heatIndex = computeHeatIndex(t, rh); 
display(); 
}
M. S. Ramaiah School of Advanced Studies 
27 
Heat index Display element 
private float computeHeatIndex(float t, float rh) { 
float index = (float)((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh)+ (0.00941695 * (t * t)) + (0.00728898 * (rh * rh))+ (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +(0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 *(rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +(0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t * t * rh * rh * rh)) -(0.0000000000481975 * (t * t * t * rh * rh * rh))); 
return index; 
} 
public void display() { 
System.out.println("Heat index is " + heatIndex); 
} 
}
M. S. Ramaiah School of Advanced Studies 28 
Java’s built in observer pattern 
Observable 
+addObserver() 
+deleteObserver() 
+notifyObservers() 
+setChanged() 
Observer 
<<Interface>> 
+update() 
WeatherData 
+getTemperature() 
+getHumidity() 
+getPressure() 
Observers 
GeneralDisplay 
+update() 
+display() 
StatisticsDisplay 
+update() 
+display() 
ForecastDisplay 
+update() 
+display() 
Subject 
Observable class keeps track of all your observers 
And notifies them for you 
1. Subject now extends the Observable class and inherits the add,delete and notifyObservers method. 
2. Object can be a Observer by implementing the Observer interface. 
3. For the Observable to send notifications 
1. First call the setChanged() to signify that the state has changed. 
2. Then call either notifyObservers() or notifyObservers(Object arg). 
4. For an Observer to receive notification implement the update() whose signature is 
1. update ( Observable o,Object arg )
M. S. Ramaiah School of Advanced Studies 
29 
Weather data to use java.util.Observable 
import java.util.Observable; 
public class WeatherData extends Observable { 
private float temperature,humidity,pressure; 
public WeatherData() { } 
public void measurementsChanged() { 
setChanged(); 
notifyObservers(); 
} 
public void setMeasurements(float temperature, float humidity, float pressure) { 
this.temperature = temperature; 
this.humidity = humidity; 
this.pressure = pressure; 
measurementsChanged(); 
} 
public float getTemperature() { 
return temperature; 
} 
public float getHumidity() { 
return humidity 
} 
public float getPressure() { 
return pressure; 
} 
}
M. S. Ramaiah School of Advanced Studies 
30 
Rework for display element 
import java.util.Observable; 
import java.util.Observer; 
public class CurrentConditionsDisplay implements Observer, DisplayElement 
{ 
Observable observable; 
private float temperature,humidity; 
public CurrentConditionsDisplay(Observable observable) { 
this.observable = observable; 
observable.addObserver(this); 
} 
public void update(Observable obs, Object arg) { 
if (obs instanceof WeatherData) { 
WeatherData weatherData = (WeatherData)obs; 
this.temperature = weatherData.getTemperature(); 
this.humidity = weatherData.getHumidity(); 
display(); 
} 
} 
public void display() { 
System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); 
} 
}
M. S. Ramaiah School of Advanced Studies 
31 
•Observer pattern can be used in any of the following situations: 
1. When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. 
2. When a change to one object requires changing others, and you don't know 
how many objects need to be changed. 
3. When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled. 
•The observer pattern provides a design where Subject and the Object are loosely coupled. 
•The power of loosely coupled is that 
–The subject knows only that Observer implements a certain interface and it doesnot need to know the concrete class of the Observer,what it does etc. 
–We can add new Observers at any time. 
–Changes to either of the subject or Observer doesnot effect each other. 
•The dark side of java.util.Observable is that it is a class, not an interface. So if it is extended then we cannot extend any other classes. This limits the reuse potential. 
•Observable protects crucial method as setChanged() is protected .So we cannot call this unless we extend the Observable class. 
•Other places where Observer pattern is used is in Swings for all ActionListener in Jbutton etc. 
Conclusion
M. S. Ramaiah School of Advanced Studies 
32 
References 
[1] “Observer Design Pattern”. [Online] 
.Available from: http://javapapers.com/design-patterns/observer-design-pattern/ (Accessed:07 September 2014) 
[2] “Observer pattern”. [Online].Available from: http://www.tutorialspoint.com/design_pattern/observer_pattern.htm 
(Accessed:07 September 2014) 
[3] “Observer design pattern in Java- Tutorial”. [Online].Available from: http://www.vogella.com/tutorials/DesignPatternObserver/article.html 
(Accessed:09 September 2014) 
[4] Gamma,E.,Helm,R.,Johnson,R.,Villsides,J.(1997)“Design Patterns- Elements of reusable Object oriented software",August 1997,Addison Wesley

Observer Pattern

  • 1.
    M. S. RamaiahSchool of Advanced Studies 1 CSN2504 Principles of Programming Presentation Observer design pattern Anshuman Biswal PT 2012 Batch, Reg. No.: CJB0412001 M. Sc. (Engg.) in Computer Science and Networking Module Leader: Dr. PVR Murthy Module Name: Principles of Programming Module Code : CSN2504
  • 2.
    M. S. RamaiahSchool of Advanced Studies 2 Marking Head Maximum Score Technical Content 05 Grasp and Understanding 05 Delivery – Technical and General Aspects 05 Handling Questions 05 Total 20
  • 3.
    M. S. RamaiahSchool of Advanced Studies 3 Presentation Outline •Introduction •A sample app: Weather monitoring system •First misguided step of development •What is wrong in the implementation •Example of observer pattern •What is observer pattern •The concept behind Observer pattern •Observer pattern- class diagram •Weather app implementation using Observer pattern •Weather app implementation using java api of Observer patternn •Conclusion •References
  • 4.
    M. S. RamaiahSchool of Advanced Studies 4 Introduction- Pattern What? •Current use comes from the work of the architect Christopher Alexander •Alexander studied ways to improve the process of designing buildings and urban areas •“Each pattern is a three-part rule, which expresses a relation between a certain context, a problem and a solution.” •Hence, the common definition of a pattern: “A solution to a problem in a context.” •Patterns can be applied to many different areas , including software development. Why patterns in Software Development? •"Designing object-oriented software is hard and designing reusable object-oriented software is even harder." - Erich Gamma •Experienced designers reuse solutions that have worked in the past •Well-structured object-oriented systems have recurring patterns of classes and objects •Knowledge of the patterns that have worked in the past allows a designer to be more productive and the resulting designs to be more flexible and reusable History: •1987 - Cunningham and Beck used Alexander’s ideas to develop a small pattern language for Smalltalk •1990 - The Gang of Four (Gamma, Helm, Johnson and Vlissides) begin work compiling a catalog of design patterns •1991 - Bruce Anderson gives first Patterns Workshop at OOPSLA(Object Oriented Programming, Systems, Languages and Applications) •1993 - Kent Beck and Grady Booch sponsor the first meeting of what is now known as the Hillside Group •1994 - First Pattern Languages of Programs (PLoP) conference •1995 - The Gang of Four (GoF) publish the Design Patterns book
  • 5.
    M. S. RamaiahSchool of Advanced Studies 5 A sample application: Weather monitoring system •The application provides three display elements : current condition, weather statistics and a simple forecast, all updated in real time as the WeatherData object acquires the most recent measurements. Also there is a need of expansion of display system in future.The job is to create an app that uses the Weather data object to update three displays for current conditions, weather stats, and a forecast. The job is to create an app that uses the WeatherData object to show the three displays for current conditions, weather stats, and a forecast. Weather station Weather Data Object Display Device Humidity sensor device Temperature sensor device Pressure sensor device Pulls data displays
  • 6.
    M. S. RamaiahSchool of Advanced Studies 6 A sample application: Weather monitoring system • The WeatherData file WeatherData +getTemperature() +getHumidity() +getPressure() +measurementChanged() These three methods return the most recent weather measurements for temperature,humidity and barometric pressure This is called when the weather measurements are updated Our task is to implement measurementChanged() so that it updates the three displays for current condition, weather stats and forecast. Also the system must be expandable i.e. other developers can add any other display elements and users can add or remove any display element as they want to the application
  • 7.
    M. S. RamaiahSchool of Advanced Studies 7 First misguided step of development public class WeatherData{ //instance variable declarations public void measurementChanged(){ float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionDisplay.update(temp,humidity,pressure); statisticsDisplay.update(temp,humidity,pressure); forecastDisplay.update(temp,humidity,pressure); } } //other weather data methods here }
  • 8.
    M. S. RamaiahSchool of Advanced Studies 8 What is wrong in the implementation ? public class WeatherData{ //instance variable declarations public void measurementChanged(){ float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionDisplay.update(temp,humidity,pressure); statisticsDisplay.update(temp,humidity,pressure); forecastDisplay.update(temp,humidity,pressure); } } //other weather data methods here } We need to encapsulate these
  • 9.
    M. S. RamaiahSchool of Advanced Studies 9 What is wrong in the implementation ? public class WeatherData{ //instance variable declarations public void measurementChanged(){ float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionDisplay.update(temp,humidity,pressure); statisticsDisplay.update(temp,humidity,pressure); forecastDisplay.update(temp,humidity,pressure); } } //other weather data methods here } We need to encapsulate these We can have a common interface to talk to the display elements …they all have the update() that will take temp,humidity and pressure values
  • 10.
    M. S. RamaiahSchool of Advanced Studies 10 What is wrong in the implementation ? public class WeatherData{ //instance variable declarations public void measurementChanged(){ float temp = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionDisplay.update(temp,humidity,pressure); statisticsDisplay.update(temp,humidity,pressure); forecastDisplay.update(temp,humidity,pressure); } } //other weather data methods here } We need to encapsulate these We can have a common interface to talk to the display elements …they all have the update() that will take temp,humidity and pressure values By coding to concrete implementation we have no way to add or remove other display elements without making changes to the program
  • 11.
    M. S. RamaiahSchool of Advanced Studies 11 Example of Observer pattern •Example: newspaper and magazine subscription •Newspaper publisher goes into business and publishes newspaper •User subscribe to the subscription and everytime there is any new edition it is delivered to the user. •User unsubscribe if they don’t want,then the news paper stops getting delivered to you. •Simillairly many users keep of subscribing and unsubscribing the news paper.
  • 12.
    M. S. RamaiahSchool of Advanced Studies 12 Observer pattern •Publisher + Subscribers = observer pattern •In observer pattern publisher is called the subject and subscriber is called the observer Times Of India Subject Varun Naveen Sujeet Observer objects Not an Observer
  • 13.
    M. S. RamaiahSchool of Advanced Studies 13 Observer pattern Times Of India Subject Varun Naveen Sujeet Observer objects
  • 14.
    M. S. RamaiahSchool of Advanced Studies 14 Observer Pattern Times Of India Subject Varun Naveen Sujeet Observer objects
  • 15.
    M. S. RamaiahSchool of Advanced Studies 15 Observer pattern Times Of India Subject Varun Naveen Sujeet Observer objects
  • 16.
    M. S. RamaiahSchool of Advanced Studies 16 Observer pattern Times Of India Subject Varun Naveen Sujeet Observer objects Not an Observer object
  • 17.
    M. S. RamaiahSchool of Advanced Studies 17 Observer pattern •Defines a one to many dependency between objects so that when one object changes state,all its dependents are notified and updated. Times Of India Subject Varun Naveen Sujeet Observer objects Dependent objects Automatic update notification Object that holds state One to many relation
  • 18.
    M. S. RamaiahSchool of Advanced Studies 18 Observer pattern : Class diagram Subject <<Interface>> +registerObserver() +removeObserver() +notifyObserver() Observer <<Interface>> +update() observers ConcreteSubject +registerObserver() +removeObserver() +notifyObserver() +getState() +setState() ConcreteObserver +update() +...() +//other observer specific methods() Subject This is the subject interface.Objects use this to register as observer and also to remove themselves from being observers Each subject can have many observers All observers need to implement the observer interface. The update() gets called when the Subject’s state changes Concrete observer can be any class that implements the Observer interface.Each Observer registers with concrete subject to receive updates A concrete Subject always implements the Subject interface.In addition to register and remove methods the concrete subject implements the notifyObserver method that is used to update all current observers whenever the state changes
  • 19.
    M. S. RamaiahSchool of Advanced Studies 19 Designing the Weather application Subject <<Interface>> +registerObserver() +removeObserver() +notifyObservers() Observer <<Interface>> +update() WeatherData +registerObserver() +removeObserver() +notifyObservers() +getTemperature() +getHumidity() +getPressure() +measurementsChanged() CurrentConditions +update() +display() StatisticsDisplay +update() +display() ForecastDisplay +update() +display() DisplayElement <<Interface>> +display() ThirdPartyDisplay +update() +display() Observers Subject All Obeserver Components implement the Observer interface.This gives the subject a common interface to talk to when it comes time to update Display interface for display elements to implement the Display interface Developers can implement the Display and the Observer interface to create their own Display element This display element shows The current condition of the Weather data This display element keeps track Of min/max/avg measurements and display them This display shows the Weather forecast based on barometer Weather data implements the Subject interface This is the subject interface
  • 20.
    M. S. RamaiahSchool of Advanced Studies 20 Designing the Weather application Subject <<Interface>> +registerObserver() +removeObserver() +notifyObservers() Observer <<Interface>> +update() WeatherData +registerObserver() +removeObserver() +notifyObservers() +getTemperature() +getHumidity() +getPressure() +measurementsChanged() CurrentConditions +update() +display() StatisticsDisplay +update() +display() ForecastDisplay +update() +display() DisplayElement <<Interface>> +display() ThirdPartyDisplay +update() +display() Observers Subject These display elements should have a pointer To the WeatherData labelled “subject”
  • 21.
    M. S. RamaiahSchool of Advanced Studies 21 Weather App implementation public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObservers(); } public interface Observer { public void update(float temp,float humidity,float pressure); } public interface DisplayElement { public void display(); }
  • 22.
    M. S. RamaiahSchool of Advanced Studies 22 Implementing subject interface in Weather Data public class WeatherData implements Subject { private ArrayList observers; private float temp,humidity,pressure; public WeatherData(){ observers = new ArrayList(); } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if(i>=0){ observers.remove(i); } }
  • 23.
    M. S. RamaiahSchool of Advanced Studies 23 @Override public void notifyObservers() { for(int i = 0;i< observers.size();i++){ Observer observer = (Observer)observers.get(i); observer.update(temp,humidity,pressure); } } public void measurementChanged(){ notifyObservers(); } public void setMeasurement(float temperature,float humidity,float pressure){ temp = temperature; this.humidity = humidity; this.pressure = pressure; measurementChanged(); } } Implementing subject interface in Weather Data
  • 24.
    M. S. RamaiahSchool of Advanced Studies 24 Build the display elements public class CurrentConditionDisplay implements Observer, DisplayElement { private float temperature,humidity; private Subject weatherData; public CurrentConditionDisplay(Subject weatherData){ this.weatherData = weatherData; weatherData.registerObserver(this); } @Override public void display() { System.out.println("Current Conditions:"+temperature +" F degrees and "+humidity+" % humidity ."); } @Override public void update(float temp, float humidity, float pressure) { this.temperature = temp; this.humidity = humidity; display(); } }
  • 25.
    M. S. RamaiahSchool of Advanced Studies 25 Lets use the Weather app public class WeatherStation { public static void main(String[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionDisplay currentDisplay = new CurrentConditionDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); weatherData.setMeasurement(80.0f, 65.0f, 30.4f); weatherData.setMeasurement(82.0f, 70.0f, 29.2f); weatherData.setMeasurement(78.0f, 90.0f, 29.2f); } }
  • 26.
    M. S. RamaiahSchool of Advanced Studies 26 Addition of HeatIndex display New requirement to provide the display element of Heat index where Heat index = ((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) + (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +(0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +(0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) +0.000000000843296 * (t * t * rh * rh * rh)) -(0.0000000000481975 * (t * t * t * rh * rh * rh))) where T is the temperature and RH is the relative humidity So just create a HeatIndexDisplay element public class HeatIndexDisplay implements DisplayElement, Observer { float heatIndex = 0.0f; private WeatherData weatherData; public HeatIndexDisplay(WeatherData weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float t, float rh, float pressure) { heatIndex = computeHeatIndex(t, rh); display(); }
  • 27.
    M. S. RamaiahSchool of Advanced Studies 27 Heat index Display element private float computeHeatIndex(float t, float rh) { float index = (float)((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh)+ (0.00941695 * (t * t)) + (0.00728898 * (rh * rh))+ (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +(0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 *(rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +(0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t * t * rh * rh * rh)) -(0.0000000000481975 * (t * t * t * rh * rh * rh))); return index; } public void display() { System.out.println("Heat index is " + heatIndex); } }
  • 28.
    M. S. RamaiahSchool of Advanced Studies 28 Java’s built in observer pattern Observable +addObserver() +deleteObserver() +notifyObservers() +setChanged() Observer <<Interface>> +update() WeatherData +getTemperature() +getHumidity() +getPressure() Observers GeneralDisplay +update() +display() StatisticsDisplay +update() +display() ForecastDisplay +update() +display() Subject Observable class keeps track of all your observers And notifies them for you 1. Subject now extends the Observable class and inherits the add,delete and notifyObservers method. 2. Object can be a Observer by implementing the Observer interface. 3. For the Observable to send notifications 1. First call the setChanged() to signify that the state has changed. 2. Then call either notifyObservers() or notifyObservers(Object arg). 4. For an Observer to receive notification implement the update() whose signature is 1. update ( Observable o,Object arg )
  • 29.
    M. S. RamaiahSchool of Advanced Studies 29 Weather data to use java.util.Observable import java.util.Observable; public class WeatherData extends Observable { private float temperature,humidity,pressure; public WeatherData() { } public void measurementsChanged() { setChanged(); notifyObservers(); } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } public float getTemperature() { return temperature; } public float getHumidity() { return humidity } public float getPressure() { return pressure; } }
  • 30.
    M. S. RamaiahSchool of Advanced Studies 30 Rework for display element import java.util.Observable; import java.util.Observer; public class CurrentConditionsDisplay implements Observer, DisplayElement { Observable observable; private float temperature,humidity; public CurrentConditionsDisplay(Observable observable) { this.observable = observable; observable.addObserver(this); } public void update(Observable obs, Object arg) { if (obs instanceof WeatherData) { WeatherData weatherData = (WeatherData)obs; this.temperature = weatherData.getTemperature(); this.humidity = weatherData.getHumidity(); display(); } } public void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); } }
  • 31.
    M. S. RamaiahSchool of Advanced Studies 31 •Observer pattern can be used in any of the following situations: 1. When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. 2. When a change to one object requires changing others, and you don't know how many objects need to be changed. 3. When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled. •The observer pattern provides a design where Subject and the Object are loosely coupled. •The power of loosely coupled is that –The subject knows only that Observer implements a certain interface and it doesnot need to know the concrete class of the Observer,what it does etc. –We can add new Observers at any time. –Changes to either of the subject or Observer doesnot effect each other. •The dark side of java.util.Observable is that it is a class, not an interface. So if it is extended then we cannot extend any other classes. This limits the reuse potential. •Observable protects crucial method as setChanged() is protected .So we cannot call this unless we extend the Observable class. •Other places where Observer pattern is used is in Swings for all ActionListener in Jbutton etc. Conclusion
  • 32.
    M. S. RamaiahSchool of Advanced Studies 32 References [1] “Observer Design Pattern”. [Online] .Available from: http://javapapers.com/design-patterns/observer-design-pattern/ (Accessed:07 September 2014) [2] “Observer pattern”. [Online].Available from: http://www.tutorialspoint.com/design_pattern/observer_pattern.htm (Accessed:07 September 2014) [3] “Observer design pattern in Java- Tutorial”. [Online].Available from: http://www.vogella.com/tutorials/DesignPatternObserver/article.html (Accessed:09 September 2014) [4] Gamma,E.,Helm,R.,Johnson,R.,Villsides,J.(1997)“Design Patterns- Elements of reusable Object oriented software",August 1997,Addison Wesley