为什么没有收到正确的数据?

Why isn't the correct data being received?

我编写了一个程序来学习和使用观察者模式,但我无法正确打印数据。它应该打印出粘贴中第 7-9 行的数据输入,但它只打印 0,0,0.

主要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());
    }

}

主题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;
    }

}

观察者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;
    }

}

您从未向主题注册您的观察者,因此notifyObserver没有观察者可通知; for 循环体永远不会执行。

添加:

weatherData.register(johnsIpad);

在你打电话之前 notifyObserver(weatherData).

我在 Observer 的构造函数中添加了这一行 class。

weatherData.register(this);

现在可以了。感谢您向我指出这一点。