这应该非常简单,但我无法让它工作。
//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()
达到阈值时打印一些东西到系统是没有问题的
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() 方法? 上述尝试导致"方法未定义"和"加热无法解决"。
方法是公共的,对象存在,观察者被注册......我错过了什么?
您需要将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();