java观察者模式
观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都得到通知并自动更新。
package observer; public interface Subject { public void register(Observer observer); public void remove(Observer observer); public void notifiedObserver(); } public interface Observer { public void update(float temp, float humidity, float pressure); } public class WeatherDate implements Subject { private float temp; private float humidity; private float pressure; private List list = null; public WeatherDate() { list = new ArrayList(); } public void register(Observer observer) { list.add(observer); } public void remove(Observer observer) { int i = list.indexOf(observer); if (i >= 0) { list.remove(i); } } public void notifiedObserver() { for (int i = 0; i < list.size(); i++) { Observer observer = (Observer) list.get(i); observer.update(temp, humidity, pressure); } } public void changeDate() { notifiedObserver(); } public void setMeasure(float temp, float humidity, float pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; changeDate(); } } public class CurrentConditionsDisplay implements Observer { private float temp; private float humidity; private float pressure; private WeatherDate wd ; public CurrentConditionsDisplay(WeatherDate wd){ this.wd = wd; wd.register(this); } public void update(float temp, float humidity, float pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; display(); } public void display(){ System.out.println("CurrentConditionsDisplay------>temp : " + temp + " humidity : " + humidity + " pressure : " + pressure); } } public class YesterdayConditionDisplay implements Observer { private float temp; private float humidity; private float pressure; private WeatherDate wd ; public YesterdayConditionDisplay(WeatherDate wd){ this.wd = wd; wd.register(this); } public void update(float temp, float humidity, float pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; display(); } public void display(){ System.out.println("YesterdayConditionDisplay------>temp : " + temp + " humidity : " + humidity + " pressure : " + pressure); } } public class WeatherStation { public static void main(String[] args) { WeatherDate weatherdate = new WeatherDate(); CurrentConditionsDisplay condition = new CurrentConditionsDisplay( weatherdate); YesterdayConditionDisplay ycd = new YesterdayConditionDisplay(weatherdate); weatherdate.setMeasure(80, 65, 70); } }