码迷,mamicode.com
首页 > 其他好文 > 详细

weather station observer

时间:2014-10-24 06:52:09      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

bubuko.com,布布扣

 

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();
}

 

public class CurrentConditionsDisplay implements Observer, DisplayElement {
  private float temperature;
  private float humidity;
  private Subject weatherData;
  public CurrentConditionsDisplay(Subject weatherData) {
  this.weatherData = weatherData;
  weatherData.registerObserver(this);
  }
  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 WeatherData implements Subject {
  private ArrayList observers;
  private float temperature;
  private float humidity;
  private float pressure;
  public WeatherData() {
  observers = new ArrayList();
}
  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)observers.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 = pressure;
  measurementsChanged();
}
// other WeatherData methods here
}

 

weather station observer

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/leetcode/p/4047304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!