public class WeatherData implements Subject{
private ArrayList<Observer> observers ;
private float temperature ;
private float humidity ;
private float pressure ;
public WeatherData(){
this .observers = new ArrayList<Observer>();
}
@Override
public void registerObserver(Observer
o) {
this .observers .add(o);
}
@Override
public void removeObserver(Observer
o) {
int i
= observers .indexOf(o);
if (i
>= 0){
observers .remove(i);
}
}
@Override
public void notifyObservers()
{
for (int i=0;
i< observers.size(); i++){
Observer o = observers .get(i);
o.update( this .temperature , this. humidity, this .pressure );
}
}
//当测量数据发送改变时,就通知这些观察者;
public void measurementChanged(){
notifyObservers();
}
//模拟实时监测数据的改变
public void setMeasurement( float temperature, float humidity, float pressure){
this .temperature =
temperature;
this .humidity =
humidity;
this .pressure =
pressure;
measurementChanged();
}
}
-----------------观察者接口
public interface Observer
{
public void update(float temp, float humidity, float pressure);
}
-----------辅助接口
public interface DisplayElement
{
public void display();
//布告板显示的时候调用这个方法;
}
--------------具体观察者
//当前天气状况布告板
public class CurrentConditionDisplay implements Observer,
DisplayElement{
private float temperature ;
private float humidity ;
private Subject weatherData ;
//用WeatherData作为构造器参数,作为注册之用
public CurrentConditionDisplay(Subject
weatherData){
this .weatherData =
weatherData;
weatherData.registerObserver( this );
}
@Override
public void display()
{
System. out .println("CurrentConditionDisplay:
" + this .temperature + "
F degrees and "
+ this .humidity + "%
humidity..");
}
@Override
public void update(float temp, float humidity, float pressure)
{
//先把状态改变保存起来,而后进行业务处理(显示)
this .temperature =
temp;
this .humidity =
humidity;
display();
}
}
------------
//测试程序,其他的布告板实现也是类似的
public class WeatherStation
{
public static void main(String[]
args) {
WeatherData data = new WeatherData();
CurrentConditionDisplay ccd = new CurrentConditionDisplay(data);
//改变主题状态
data.setMeasurement(80, 50, 100);
}
}