Observer mode java
The following is an implementation based on HeadFirst:
Topic and observer. Three interfaces are displayed.
public interface Observer {public void update(float temp, float humidity, float pressure);}public interface Subject {public void registerObserver(Observer o);public void removeObserver(Observer o);public void notifyObserver();}public interface DisplayElement {public void display();}
Topic interface for meteorological data Implementation
public class Weather implements Subject {private ArrayList
observer;private float pressure;private float humidity;private float temp;public Weather() {observer = new ArrayList
();}@Overridepublic void registerObserver(Observer o) {observer.add(o);}@Overridepublic void removeObserver(Observer o) {int i = observer.indexOf(o);if (i >= 0)observer.remove(i);}@Overridepublic void notifyObserver() {for (int i = 0; i < observer.size(); i++) {observer.get(i).update(temp, humidity, pressure);}}public void measurementChanged() {notifyObserver();}public void setMeasurement(float temp, float humidity, float pressure) {this.temp = temp;this.humidity = humidity;this.pressure = pressure;measurementChanged();}}
With the weather, it is displayed on the bulletin board, implementing the observer and display interface.
public class CurrentConditionDisplay implements Observer, DisplayElement {private float temp;private float humidity;private Subject weatherData;public CurrentConditionDisplay(Subject weatherData) {super();this.weatherData = weatherData;weatherData.registerObserver(this);}@Overridepublic void display() {System.out.println("Current conditions :"+temp+"F degrees and"+humidity+"%humidity");}@Overridepublic void update(float temp, float humidity, float pressure) {this.temp = temp;this.humidity = humidity;display();}}
Final Test
public class WeatherStation {/** * @author WXQ * @param args */public static void main(String[] args) {Weather weather = new Weather();CurrentConditionDisplay currentcd = new CurrentConditionDisplay(weather);weather.setMeasurement(80, 65, 30.4f);weather.setMeasurement(82, 63, 23.4f);weather.setMeasurement(82, 67, 32.4f);}}
The result is displayed
Current conditions: 80366f degrees and65.0 % humidity
Current conditions: 82.0F degrees and63.0 % humidity
Current conditions: 82.0F degrees and67.0 % humidity