简体   繁体   English

动作侦听器是否应属于他们所申请的课程?

[英]Should action listeners be in the class they apply to?

I'm programming a web browser with multiple classes. 我正在对具有多个类的Web浏览器进行编程。 One class is "navbar" which holds most of the buttons such as search, back, forward, etc. The navbar class has action listeners which, when the search button is pressed, become active, and lead to the production of a URL, which needs to be passed to the JEditorPane, but the editor pane is in a different class, "editor". 一类是“导航栏”,其中包含大多数按钮,例如搜索,后退,前进等。导航栏类具有动作侦听器,当按下搜索按钮时,该动作侦听器将变为活动状态,并导致生成URL,该URL需要传递给JEditorPane,但编辑器窗格在另一个类“编辑器”中。

It does not make sense for an editor to be instantiated inside navbar, so how can i pass the variable from the navbar class to the editor class? 在navbar内实例化编辑器没有意义,因此如何将变量从navbar类传递给编辑器类?

Is it okay to use statics in this situation? 在这种情况下可以使用静态方法吗?

Why not simply give the nav bar a reference to the editor? 为什么不简单地给导航栏提供对编辑器的引用? This could be done in the constructor, if the editor is instantiated first, or via getter/setter pair (actually, only the setter is really needed...). 如果首先实例化了编辑器,则可以在构造函数中完成此操作,也可以通过getter / setter对(实际上,只需要setter即可)。 If the nav bar has such a reference, it can call the appropriate methods from within the listener implementation. 如果导航栏具有此类引用,则可以从侦听器实现中调用适当的方法。

class Editor { ... }
class NavBar implements ActionListener
{
    public NavBar(Editor editor)
    {
        myEditor = editor;
    }
    public void actionPerformed (ActionEvent e)
    {
        // call methods of myEditor
    }

    private Editor myEditor;
}

Editor theEditor = new Editor();
NavBar theNavBar = new NavBar(theEditor);

You can use some kind of intermediate interface between these, typically a service like layer. 您可以在这些之间使用某种中间接口,通常是类似服务的层。 Which is basically what the observer pattern is as well. 基本上,观察者模式也是如此。 The editor could list events the navbar produces, but that also means later on you could also catch these events in other components 编辑器可以列出导航栏产生的事件,但这也意味着以后您还可以在其他组件中捕获这些事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM