从观察者调用方法

Call methods from observer

这应该很简单,但我无法让它工作。

//decreases the temperature automatically over time
Heating heating = new Heating(25);
//SHOULD watch when the temp drops below a threshold
Observer watcher = new Watcher();
heating.addObserver(watcher);

暖气有

public void turnOn()

public void turnOff()

达到阈值时向sysout打印一些东西是没有问题的

    class Watcher implements Observer {


    private static final int BOTTOM_TEMP = 23;

    @Override
    public void update(Observable o, Object arg) {

        double temp = Double.parseDouble(arg.toString());

        if (temp < BOTTOM_TEMP) {
            //System.out.println("This works! The temperature is " + temp);
            o.turnOn();  //doesn't work
            heater.turnOn();  //doesn't work either
        }
    }
}

所以,简而言之:如何从观察者内部调用可观察对象的 turnOn() 方法?上述尝试导致 "method undefined" 和 "heating cannot be resolved".

方法是public,对象存在并且观察者已注册... 我错过了什么?

您需要将 Observable 转换为 Heating 才能调用属于 Heating 对象的方法。像这样:

if (temp < BOTTOM_TEMP) {
  //System.out.println("This works! The temperature is " + temp);
  if (o instanceof Heating){
    ((Heating)o).turnOn(); 
  }
}

Observable 接口不包含这些方法,因此您需要转换它:

((Heating) o).turnOn();