1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| public interface WeatherSubject { void registerObserver(WeatherObserver o); void removeObserver(WeatherObserver o); void notifyObserver(); }
public class WeatherData implements WeatherSubject {
private List<WeatherObserver> observers; private float temperature; private float humidity; private float pressure;
public WeatherData() { observers = new ArrayList<>(); }
public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure;
notifyObserver(); } @Override public void registerObserver(WeatherObserver o) { observers.add(o); }
@Override public void removeObserver(WeatherObserver o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } }
@Override public void notifyObserver() { for (WeatherObserver o : observers) { o.update(temperature, humidity, pressure); } } }
public interface WeatherObserver { void update(float temp, float humidity, float pressure); }
public class StatisticsDisplay implements WeatherObserver {
public StatisticsDisplay(WeatherSubject weatherData) { weatherData.registerObserver(this); }
@Override public void update(float temp, float humidity, float pressure) { System.out.println("StatisticsDisplay.update " + temp + " " + humidity + " " + pressure); } }
public class CurrentConditionDisplay implements WeatherObserver {
public CurrentConditionDisplay(WeatherSubject weatherData) { weatherData.registerObserver(this); }
@Override public void update(float temp, float humidity, float pressure) { System.out.println("CurrentConditionDisplay.update " + temp + " " + humidity + " " + pressure); } }
public class WeatherStation {
public static void main(String[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionDisplay currentConditionDisplay = new CurrentConditionDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
weatherData.setMeasurements(0, 0, 1); weatherData.setMeasurements(1, 1, 2); } }
|
Related Issues not found
Please contact @mvpsheng to initialize the comment