观察者模式
定义:出版者+订阅者=观察者模式
出版者称为“主题”,订阅者称为“观察者”。
上代码:
//=========主题接口============
public interface Subject{
//注册观察者
public void registerObserver(Observer o);
//移除观察者
public void removeObserver(Observer o);
//主题改变,通知观察者
public void notifyObservers();
}
//=========观察者接口==========
public interface Observer{
//当气象值改变时,主题会把这些状态值当作方法的参数,传送给观察者
public void update(float temp,float humidity,float pressure);
}
//=========当布告板需要显示时调用此方法========
public interface DisplayElement{
public void display();
}
//weatherData 实现主体接口
public class WeatherData implements Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public weatherData(){
observers = new ArrayList();
}
//注册为观察者
public void registerObserver(Observer o){
observers.add(o);
}
//移除观察者
public void removeObserver(Observer o){
int i = observers.indexof(o);
if(i >= 0){
observers.remouve(i);
}
observers.remouve(o);
}
//通知观察者
public void notifyObservers(){
for(int i = 0;i<observers.size();i++){
Observer observe = observers.get(i);
observe.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 class CurrentConditionsDisplay implements Observer,DisplayElement{
private float temperature;
private float humidity;
private Subject weatherData;
//构造方法
public CurrentConditionsDisplay(){
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
//更新各个状态
public void update(float temperature,float humidity,private pressure){
this.temperature =temperature;
this.humidity = humidity;
this.pressure = pressure;
display();
}
//显示
public void display(){
System.out.println("");
}
}
//启动气象站
public class weatherStation{
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay a = new CurrentConditionsDisplay();//布告板1
CurrentConditionsDisplay b = new CurrentConditionsDisplay();//布告板2
CurrentConditionsDisplay c = new CurrentConditionsDisplay();//布告板3
weatherData.setMeasurements(80,65);
}