观察者模式定义:观察者模式定义了一系列对象之间的一对多关系,当一个对象状态改变,其他依赖者都会收到通知。标签:weatherData,void,float,观察者,模式,humidity,案例,public From: https://blog.51cto.com/u_12026373/5930790
气象站要想多个公告版发送信息,实现每当气象站数据改变时公告板就能自动去更新自己的数据。
主题接口,用来添加公告板或者删除公告吧,信息变化
public interface Subject {
//这两个方法都需要一个观察者作为变量,该观察者是用来注册或被删除的
public void registerObserver(Observer o);
public void removeObserver(Observer o);
//当主题状态改变是,这个方法会被调用,以通知所有的观察者。
public void notifyObservers();
}public class WeatherData implements Subject{
private ArrayList<Observer> observers;//用于存储观察者
//观察者观察的参数
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){//初始化
observers=new ArrayList<>();
}
//注册一个观察者就放入容器中
@Override
public void registerObserver(Observer o) {
// TODO Auto-generated method stub
observers.add(o);
}
//从容器中移除观察者
@Override
public void removeObserver(Observer o) {
// TODO Auto-generated method stub
int i=observers.indexOf(o);
if(i>=0){
observers.remove(i);
}
}
//当前状态改变的话,就去调用观察者的更新函数
@Override
public void notifyObservers() {
// TODO Auto-generated method stub
for(int i=0;i<observers.size();i++){
Observer observer=(Observer)observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
public void measurementsChanged(){
notifyObservers();
}
//改变参数
public void setMeasurements(float temperature,float humidity,float pressure){
this.temperature=temperature;
this.humidity=humidity;
this.pressure=pressure;
measurementsChanged();
}
}
public interface Observer {
//所有的观察者都必须实现update()方法,以实现观察者接口。在这里
//把观测值传入观察者
public void update(float temp,float humidity,float pressure);
}public interface DisplayElement {
//用于具体的显示
public void display();
}
public class CurrentConditionsDisplay implements Observer,DisplayElement{
//需要的参数
private float temperature;
private float humidity;
private Subject weatherData;
//把自己作为观察者注册入主题
public CurrentConditionsDisplay(Subject weatherData){
this.weatherData=weatherData;
weatherData.registerObserver(this);
}
//调用显示
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Current conditions: "+temperature+
"F degrees and "+humidity+"% humidity");
}
//用于更新,更新完之后自动显示
@Override
public void update(float temperature, float humidity, float pressure) {
// TODO Auto-generated method stub
this.temperature=temperature;
this.humidity=humidity;
display();
}
}测试:
public static void main(String[] args) {
// TODO Auto-generated method stub
WeatherData weatherData=new WeatherData();
CurrentConditionsDisplay currentDisplay=
new CurrentConditionsDisplay(weatherData);
CurrentConditionsDisplay currentDisplay1=
new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65,30.5f);
weatherData.setMeasurements(82, 70,29.2f);
weatherData.setMeasurements(78, 90,29.2f);
}