如何使用监听器创建事件处理程序类并在java中注册



我想用事件逻辑在File和FileView之间创建连接。

我创建了新的类eventHandler。

我希望文件在他完成创建时激发事件,然后我希望调用FileView,因为FileView已在eventHandler中注册。

我知道如何在javascript中实现,但不知道如何在java中实现

其想法是执行ViewPart->(侦听)EventHandler->(侦听)File你知道我如何用java实现这个逻辑吗?

 class File {
   private String path;
   private String name;
   public File(){
      path = calcPath();
      name = calcName()
      finish() -> fire the event to eventHandler
    }
   public finish() {
        // fire event to eventHandler
   }
..............
  }

  class FileView extends ViewPart {
         // Should register to listen to event in the eventHandler
        public functionShouldListenToEvent() {
               // need to register to event of eventHandler
           }
       public functionThatShouldTrigger(){
                //updateMyview
       }
   }

   class eventHandler{
            //Should keep the event that we register and also the listener
            //Should somehow get the event and check who is listen and the fire the event to the listeners 
    }

如果我答对了你的问题,你想要这样的东西:

class File {
    private FileEventListener listener; // <- create getter/setter for this
    public finish() {
        listener.onFileFinished();
    }
}

class FileView extends ViewPart implements EventProxyListener {
    private EventProxy proxy = new EventProxy();
    // This is where you register this FileView as a listener to events from the proxy instance
    public FileView() {
        proxy.setListener(this); // <- This is ok because FileView implements EventProxyListener
    }
    // Implements onFinished, described in the EventProxyListener interface
    public void onProxyFinished() {
        // EventProxy has reported that it is done
    }
}
// This is the MiM-class that will clobber your code. I urge you to reconsider this design
class EventProxy implements FileEventListener {
    private EventProxyListener listener; // <- Create getter/setter for this
    private File file = new File();
    public EventProxy {
        file.setListener(this);
    }
    public void onFileFinished() {
        listener.onProxyFinished();
    }
}
interface EventProxyListener {
    public void onProxyFinished();
}
interface FileEventListener {
    public void onFileFinished();
}

当然,应该有更多的错误处理和内容,但你明白要点了。。。

如果我弄错了你的问题,请告诉我。

和平!

最新更新