码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式之观察者模式(java内置)

时间:2015-08-21 23:27:57      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:设计模式

技术分享
DisplayElement.java,WeatherStation.java同上
WeatherData.java

import java.util.Observable;

public class WeatherData extends Observable {

    private float temperature;
    private float humidity;
    private float pressure;

    public float getTemperature() {
        return temperature;
    }

    public float getHumidity() {
        return humidity;
    }

    public float getPressure() {
        return pressure;
    }

    public WeatherData() {
    }

    public void measurementsChanged(){
        setChanged();
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }   
}

CurrentConditionDisplay.java

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

public class CurrentConditionDisplay implements Observer, DisplayElement {
-
    private float temperature;
    private float humidity;
    Observable observable;

    public CurrentConditionDisplay(Observable observable) {
            this.observable = observable;
            observable.addObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Current Conditions:" + temperature
                + "F degrees and " + humidity + "% humidity");
    }

    @Override
    public void update(Observable obs, Object arg) {
        if (obs instanceof WeatherData) {
            WeatherData weatherData = (WeatherData) obs;
            this.temperature = weatherData.getTemperature();
            this.humidity = weatherData.getHumidity();
            display();
        }
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

设计模式之观察者模式(java内置)

标签:设计模式

原文地址:http://blog.csdn.net/zhou554291911/article/details/47842945

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!