Keeping ur object in the know-------The Observer Pattern
![]() |
The three players in the system are the weather station, the WeatherData object,and the display that shows users the current weather conditions. The WeatherData object konws how to talk to the physical Weather Station, to get updated data. The WeatherData object then updates its displays for the three different display elements: Current Conditions,Weather Statistics, and a simple forecast. |
The Observer Pattern:

public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
//This method is called to notify all observers
// when the subject's state has changed.
}
public interface Observer{
public void update (float temp, float humidity, float presure);
}
public interface DisplayElement{
public void display();
}
public class WeatherData implements Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public void registerObserver(Observer o){
observers.add(o);
}
public void removeObserver(Observer o){
int i=observers.indexOf(o);
if (i>=0) observers.remove(i);
}
public void notifyObservers(){
for (int i=0;i<observers.size();i++){
Observer observer=(Observer)observer.get(i);
Observer.update(temperature,humidity,pressure);
}
}
public void measurementsChanged(){
notifyObservers();
}
public void setMeasurements(float temperature,float humidity,float pressure){
this.temperature=temperature;
this.humidity=humidity;
this.pressure=pressurel
measurementsChanged();
}
//other WeatherData methods here
}
public class CurrentConditionsDisplay implements Observer,DisplayElement{
private float temerature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData){
this.weatherData=weatherData;
weatherData.registerObserver(this);
//The constructor is passed the WeatherData object (the Subject)
//and we use it to register the display as an observer.
}
public void update (float temperature,float humidity,float pressure){
this.temperature=temperature;
this.humidity=humidity;
display();
}
public void display(){
System.out.println("Current conditions:"+temperature+"F degrees and "+humidity+"%humidity");
}
}
public class WeatherStation{
public static void main(String[] args){
WeatherData weatherData =new WeatherData();
CurrentConditionsDisplay curentDisplay=
new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80,65,30.4f);
}
}



浙公网安备 33010602011771号