1. 主题 package com.feng.design.observer; import java.util.Observable; public class WeatherData extends Observable { private float temperature; private float humidity; private float presure; public void measurementChanged() { this.setChanged(); this.notifyObservers(); } public void setMeasurement(float temperature, float humidity, float presure) { this.temperature = temperature; this.humidity = humidity; this.presure = presure; measurementChanged(); } public float getTemperature() { return temperature; } public float getHumidity() { return humidity; } public float getPresure() { return presure; } } 2. 观察者 package com.feng.design.observer; import java.util.Observable; import java.util.Observer; public class CurrentConditionsDisplay implements Observer { private float temperature; private float humidity; public CurrentConditionsDisplay(WeatherData weather) { weather.addObserver(this); } @Override public void update(Observable o, Object arg) { if(o instanceof WeatherData) { WeatherData weather = (WeatherData)o; temperature = weather.getTemperature(); humidity = weather.getHumidity(); this.display(); } } public void display() { System.out.println(this.toString() + " tempeature:" + this.temperature + " humidity:" + this.humidity); } } 3 Test package com.feng.design.observer; public class Test { public static void main(String[] args) { WeatherData weather = new WeatherData(); CurrentConditionsDisplay condition = new CurrentConditionsDisplay(weather); weather.setMeasurement(12L, 111L, 333L); CurrentConditionsDisplay condition1 = new CurrentConditionsDisplay(weather); weather.setMeasurement(122L, 341L, 333L); } } 4 Console print com.feng.design.observer.CurrentConditionsDisplay@4a5ab2 tempeature:12.0 humidity:111.0 com.feng.design.observer.CurrentConditionsDisplay@167d940 tempeature:122.0 humidity:341.0 com.feng.design.observer.CurrentConditionsDisplay@4a5ab2 tempeature:122.0 humidity:341.0 |
|
来自: Bradypod > 《design pattern》