分享

Observer pattern

 Bradypod 2013-10-19
1. 主题
package com.feng.design.observer;

import java.util.Observable;

public class WeatherData extends Observable {

private float temperature;
private float humidity;
private float presure;
public void measurementChanged() {
this.setChanged();
this.notifyObservers();
}
public void setMeasurement(float temperature, float humidity, float presure) {
this.temperature = temperature;
this.humidity = humidity;
this.presure = presure;
measurementChanged();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPresure() {
return presure;
}
}
2. 观察者
package com.feng.design.observer;

import java.util.Observable;
import java.util.Observer;

public class CurrentConditionsDisplay implements Observer {

private float temperature;
private float humidity;
public CurrentConditionsDisplay(WeatherData weather) {
weather.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
if(o instanceof WeatherData) {
WeatherData weather = (WeatherData)o;
temperature = weather.getTemperature();
humidity = weather.getHumidity();
this.display();
}
}
public void display() {
System.out.println(this.toString() + "  tempeature:" + this.temperature + "  humidity:" + this.humidity);
}

}
3 Test
package com.feng.design.observer;

public class Test {

public static void main(String[] args) {
WeatherData weather = new WeatherData();
CurrentConditionsDisplay condition = new CurrentConditionsDisplay(weather);
weather.setMeasurement(12L, 111L, 333L);
CurrentConditionsDisplay condition1 = new CurrentConditionsDisplay(weather);
weather.setMeasurement(122L, 341L, 333L);
}
}
4 Console print
com.feng.design.observer.CurrentConditionsDisplay@4a5ab2  tempeature:12.0  humidity:111.0
com.feng.design.observer.CurrentConditionsDisplay@167d940  tempeature:122.0  humidity:341.0
com.feng.design.observer.CurrentConditionsDisplay@4a5ab2  tempeature:122.0  humidity:341.0

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多