用观察者模式设计一个气象台
观察者模式
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
背景
气象站测量气象数据为客户提供多种气象布告信息服务,为此气象站希望通过自己提供的 气象数据 为客户开发不同的布告版的应用软件,包括 目前状况布告版、简单预报布告版、气象统计布告版 等,并且当得到新的气象数据测量结果后,每个客户订购的布告版信息都应实时更新。
部分代码
Subject.java
package WeatherStationDemo;
import java.util.ArrayList;
public abstract class Subject {
protected ArrayList<Observer> observers = new ArrayList<Observer>();
public abstract void notifyObserver();//通知
public abstract void registerObserver(Observer o); //注册
public abstract void removeObserver(Observer o); //移除
}
WeatherData.java
package WeatherStationDemo;
public class WeatherData extends Subject{
private double temperature;
private double humidity;
private double pressure;
public WeatherData() {
}
//getter/setter方法
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public double getHumidity() {
return humidity;
}
public void setHumidity(double humidity) {
this.humidity = humidity;
}
public double getPressure() {
return pressure;
}
public void setPressure(double pressure) {
this.pressure = pressure;
}
public void setMeasurements(double temperature,double humidity,double pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
}
/*
* public boolean measurementsChanged() { System.out.println("气象数据变更……"); flag =
* true; return flag; }
*/
@Override
public void notifyObserver() {
for(Observer o : observers) {
o.update();
}
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
}
Observer.java
package WeatherStationDemo;
public abstract class Observer {
protected WeatherData weatherData;
public abstract void update();
}
CurrentSituationDisplay.java
package WeatherStationDemo;
public class CurrentSituationDisplay extends Observer{
public CurrentSituationDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
}
@Override
public void update() {
System.out.println("——————目前状况布告板——————");
System.out.println("目前的气温:"+ weatherData.getTemperature() + "℃");
System.out.println("目前的湿度:"+ weatherData.getHumidity() + "%");
System.out.println("目前的气压:"+ weatherData.getPressure() + "kpa");
}
}
Client.java
package WeatherStationDemo;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
WeatherData weatherData = new WeatherData();
weatherData.setMeasurements(25.3, 90, 102.5);
Observer currentObserver = new CurrentSituationDisplay(weatherData);
Observer statisticsObserver = new WeatherStatisticsDispaly(weatherData);
Observer forecastObserver = new SimpleForecastDisplay(weatherData);
weatherData.registerObserver(currentObserver);
weatherData.registerObserver(statisticsObserver);
weatherData.registerObserver(forecastObserver);
weatherData.notifyObserver();
}
}
Client运行展示
技术有限…有不合理之处,见谅(○´・д・)ノ