Head First设计模式笔记(观察者模式--jdk自带实现)

1.主题类

package com.TWO;

import java.util.Observable;

public class WeatherData extends Observable {

    private float temp;
    private float humidity;
    private float pressure;

    public WeatherData(){}


    public void measurementsChanged(){
        //在调用notifyObservers()之前,要先调用setChanged来指示状态已经改变
        setChanged();
        notifyObservers();
    }

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

    public float getTemperature(){
        return temp;
    }
    public float getHumidity(){
        return humidity;
    }
    public float getPressure(){
        return pressure;
    }

}

2.观察者

package com.TWO;

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

public class CurrentConditionsDisplay implements Observer{

    Observable observable;
    private float temp;
    private float humidity;

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

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

    }

    public void display(){
        System.out.println("temp = "+ temp +";humidity = "+ humidity);
    }

}

测试类

package com.TWO;

public class Main {

    public static void main(String[] args){

        WeatherData weatherData = new WeatherData();

        new CurrentConditionsDisplay(weatherData);

        //模拟数据变化
        weatherData.setMeasurements(30, 40, 50);
    }

}

你可能感兴趣的:(java)