Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从观察者调用方法_Java_Observer Pattern - Fatal编程技术网

Java 从观察者调用方法

Java 从观察者调用方法,java,observer-pattern,Java,Observer Pattern,这应该很简单,但我不能让它工作 //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() 及 当达

这应该很简单,但我不能让它工作

//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()

当达到阈值时,将某些内容打印到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
        }
    }
}
类观察者实现观察者{
专用静态最终内部温度底部温度=23;
@凌驾
公共无效更新(可观察o,对象arg){
double temp=double.parseDouble(arg.toString());
如果(温度<底部温度){
//System.out.println(“这是可行的!温度是”+temp);
o、 打开();//不起作用
加热器。打开();//也不工作
}
}
}
简而言之,我如何从观察者内部调用可观察对象的turnOn()方法?上述尝试导致“方法未定义”和“加热无法解决”

方法是公共的,对象存在,并且观察者已注册。。。
我缺少什么?

您需要将
observeable
强制转换为
Heating
,以便调用属于
Heating
对象一部分的方法。像这样:

if (temp < BOTTOM_TEMP) {
  //System.out.println("This works! The temperature is " + temp);
  if (o instanceof Heating){
    ((Heating)o).turnOn(); 
  }
}
if(温度<底部温度){
//System.out.println(“这是可行的!温度是”+temp);
if(o加热实例){
((加热)o.打开();
}
}

您需要将
可观察的
强制转换为
加热
,以便调用属于
加热
对象的方法。像这样:

if (temp < BOTTOM_TEMP) {
  //System.out.println("This works! The temperature is " + temp);
  if (o instanceof Heating){
    ((Heating)o).turnOn(); 
  }
}
if(温度<底部温度){
//System.out.println(“这是可行的!温度是”+temp);
if(o加热实例){
((加热)o.打开();
}
}

可观察的
界面不包含这些方法,因此您需要强制转换它:

((Heating) o).turnOn();

Observable
界面不包含这些方法,因此您需要强制转换它:

((Heating) o).turnOn();