观察者模式由2部分组成 主题 和 观察者
1 主题接口
package com.observer;
/***
*
* @author shasha
* 观察者主题类
*/
public interface Subject {
public void registObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
2 天气预报主题 (实现了主题接口)
package com.observer;
import java.util.ArrayList;
/**
*
* @author shasha
* 主题实现类---天气预报主题
*/
public class WeatherData implements Subject {
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers=new ArrayList<Observer>();
}
@Override
public void notifyObservers() {
// TODO Auto-generated method stub
for(int i=0;i<observers.size();i++){
Observer observer=observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
@Override
public void registObserver(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(o);
}
}
public void setMeasurements(float temperature,float humidity,float pressure){
this.temperature=temperature;
this.humidity=humidity;
this.pressure=pressure;
measurementsChanged();
}
public void measurementsChanged(){
notifyObservers();
}
}
3 观察者接口
package com.observer;
/**
*
* @author shasha
* 观察者
*/
public interface Observer {
public void update(float temp,float humidity,float pressure);
}
4 显示信息接口
package com.observer;
/***
*
* @author shasha
* 显示接口
*
*/
public interface DisplayElement {
public void display();
}
5 观察者实现类----天气预报显示版
package com.observer;
/***
*
* @author duwan
* 天气预报显示板
*/
public class CurrentConditionDisplay implements DisplayElement,Observer{
private float temperature;
private float humidity;
private Subject weatherdate;
public CurrentConditionDisplay(Subject weatherdata){
this.weatherdate=weatherdata;
weatherdata.registObserver(this);
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("temperature: "+temperature+" F degress and"+humidity+"% humidity");
}
@Override
public void update(float temp, float humidity, float pressure) {
// TODO Auto-generated method stub
this.temperature=temp;
this.humidity=humidity;
display();
}
}
6 测试程序 气象站
package com.observer;
/**
*
* @author shasha
* 气象站测试程序
*/
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData=new WeatherData();
CurrentConditionDisplay ccd=new CurrentConditionDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
}
}
--------针对需求 可以在
public void measurementsChanged(){
notifyObservers();
}
增加一个setChange() 与java.util.Observser中一样 完成一定情况下才提醒观察者