Why isn't the correct data being received?

时间:2016-07-11 21:51:53

标签: java observer-pattern

I wrote a program to learn and play with the observer pattern, but I'm having trouble with the data being printed out correctly. It should print out the data input at lines 7-9 in the paste, but instead it just prints 0,0,0.

Main class

public class ObserverPattern {

    public static void main(String[] args) {
        Subject weatherData = new Subject();
        weatherData.setTemp(81);
        weatherData.setHumidity(14);
        weatherData.setWindSpeed(8);

        Observer johnsIpad = new Observer(weatherData);

        weatherData.notifyObserver();

        System.out.println(johnsIpad.toString());
    }

}

Subject Class

import java.util.ArrayList;

public class Subject {

    // fields
    ArrayList<Observer> observers;
    public double temp;
    public double humidity;
    public double windSpeed;

    // Constructor
    public Subject() {
        observers = new ArrayList<Observer>();
    }

    // Observer pattern methods
    public void register(Observer o) {
        observers.add(o);
    }

    public void unregister(Observer o) {
        observers.remove(observers.indexOf(o));
    }

    public void notifyObserver() {
        for (Observer observer : observers) {
            observer.update(temp, humidity, windSpeed);
        }
    }

    // set weather data
    public void setTemp(double temp) {
        this.temp = temp;
    }

    public void setHumidity(double humidity) {
        this.humidity = humidity;
    }

    public void setWindSpeed(double windSpeed) {
        this.windSpeed = windSpeed;
    }

}

Observer Class

public class Observer {

    double temp;
    double humidity;
    double windSpeed;

    Subject weatherData;

    Observer(Subject weatherDataSource) {
        weatherData = weatherDataSource;
    }

    public void update(double temp, double humidity, double windSpeed) {
        this.temp = temp;
        this.humidity = humidity;
        this.windSpeed = windSpeed;
    }

    public String toString() {
        return temp + "\n" + humidity + "\n" + windSpeed;
    }

}

2 个答案:

答案 0 :(得分:2)

You never register your observer with the subject, so notifyObserver has no observers to notify; the for loop body never executes.

Add:

weatherData.register(johnsIpad);

before you call notifyObserver(weatherData).

答案 1 :(得分:0)

I added this line to the constructor in the Observer class.

weatherData.register(this);

Now it works. Thanks for pointing that out to me.