如何使用listener创建事件处理程序类并在java中注册?

时间:2013-11-28 22:06:32

标签: java

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

我创建了新的类eventHandler。

我希望文件在完成创建后会触发事件,然后我希望调用FileView,因为FileView是在eventHandler中注册的。

我知道如何在javascript中执行此操作但不在java中执行此操作

想法是做ViewPart->(监听)EventHandler->(监听)文件 你知道如何在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 
    }

1 个答案:

答案 0 :(得分:1)

如果我的问题正确,你需要这样的事情:

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

当然,应该有更多的错误处理和东西,但你得到了要点......

如果我的问题出错,请告诉我。

和平!