首页 > 代码库 > weather station observer
weather station observer
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 =http://www.mamicode.com/ 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。