观察者:
public interface Observer { void update(float temperature, float humidity, float pressure); }
主体;
public interface Subject { public void registerObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObserver(); }
变更的数据:
public class WeatherData implements Subject{ private List<Observer> observers; private float temperature; private float humidity; private float pressure; public WeatherData() { this.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(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { int i = observers.indexOf(observer); if (i >= 0){ observers.remove(observer); } } @Override public void notifyObserver() { for (Observer o : observers) { o.update(temperature,humidity,pressure); } } }
被观察者1:
public class CurrentConditionsDisplay implements Observer{ public CurrentConditionsDisplay(Subject weatherData) { weatherData.registerObserver(this); } @Override public void update(float temperature, float humidity, float pressure) { System.out.println("CurrentConditionsDisplay update:"+temperature+" "+humidity+" "+pressure); } }
被观察者2:
public class StatisticsDisplay implements Observer{ /** * 订阅天气数据 * @param weatherData */ public StatisticsDisplay(Subject weatherData){ weatherData.registerObserver(this); } public void update(float temp, float humidity, float pressure){ System.out.println("StatisticsDisplay update:"+temp+" "+humidity+" "+pressure); } }
标签:temperature,void,float,观察者,模式,humidity,pressure,public From: https://www.cnblogs.com/yb-ken/p/18067191