匿名内部类:它们什么时候(不)合适?

发布于 2024-12-20 22:17:16 字数 764 浏览 5 评论 0原文

以下面的例子为例。我想使用一个对象,将其称为DoodadDoodad 元素对浏览器事件的处理实现得很差。 Doodad 的典型实例化为 Doodad someDoodad = new Doodad();。显然这不适合我的需求,因为事件处理很差。我是否适合重写 onBrowserEvent() 方法,如下所示:

Doodad someDoodad = new Doodad() {
@Override
  public void onBrowserEvent(Event event) {
      switch (DOM.eventGetType(event)) {
          case Event.ONDBLCLICK:
          case Event.ONFOCUS:
          case Event.ONCLICK:
              if (!isEnabled()) {
                  return;
              }
              break;
      }
      super.onBrowserEvent(event);
  }
};

显然这是一个简单的示例,但什么时候我不想想要使用匿名内部类?它是否被明确禁止或不可能?

我看到第一个问题有很多答案,但到目前为止没有一个答案回答第二个问题:是否明确禁止或不可能使用匿名内部类?

Take the following example. There's an object I want to use, call it a Doodad. Doodad elements have poorly implemented handling of browser events. Typical instantiation of a Doodad would be Doodad someDoodad = new Doodad();. Obviously this isn't suiting my needs because of the poor event handling. Is it appropriate for me to override the onBrowserEvent() method, like so:

Doodad someDoodad = new Doodad() {
@Override
  public void onBrowserEvent(Event event) {
      switch (DOM.eventGetType(event)) {
          case Event.ONDBLCLICK:
          case Event.ONFOCUS:
          case Event.ONCLICK:
              if (!isEnabled()) {
                  return;
              }
              break;
      }
      super.onBrowserEvent(event);
  }
};

Obviously this is a simple example, but when might I not want to use an anonymous inner class? Is it ever explicitly disallowed or impossible?

I'm seeing lots of answers to the first question, but none of the answers so far answer the second: Is it ever explicitly disallowed or impossible to use an anonymous inner class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

俏︾媚 2024-12-27 22:17:16

通常,匿名内部类的最佳用法是当您只想创建该类的特定实现的一个实例时。而且实现非常简单。理想情况下,它应包含 1-2 行代码。

在你的情况下,尽管你的方法 onBrowserEvent() 超过 2 行,但它仍然没问题。

Typically the best usage of anonymous inner classes is when you want to create only one instance of specific implementation of this class. And when the implementation is pretty simple. Ideally it should contain 1-2 lines of code.

In your case it is still OK although your method onBrowserEvent() is longer than 2 lines.

带刺的爱情 2024-12-27 22:17:16

匿名内部类是 Java 创建闭包的语法。下面是一个大概的示例:

interface Adder {
  int add(int arg);
}

...

Adder createAdder(int n) {
   final int nf = n;
   return new Adder() { 
       int add(int arg) { return arg + nf; } 
   }
}

createAdder 方法创建了一个本质上是一个函数,使用闭包来捕获传递的值 n。闭包在函数式编程中很重要,函数式编程正试图使其成为主流。这就是为什么每个人都在尖叫我们需要 Java 中的“真正的”闭包(即比我的示例中的语法更好)。

(当然,我不是在回答所提出的问题;我想我想说的是,匿名类对于我上面描述的内容很有用。对于几乎所有其他内容,我都会创建一个命名内部类,因为如果有任何名称是自记录的我认为更容易阅读)

Anonymous inner classes is Java's syntax for creating closures. Here's an approximate example:

interface Adder {
  int add(int arg);
}

...

Adder createAdder(int n) {
   final int nf = n;
   return new Adder() { 
       int add(int arg) { return arg + nf; } 
   }
}

Method createAdder creates what essentially is a function using a closure to capture the passed value n. Closures are important in functional programming which is trying to make it into mainstream. This is why everyone is screaming that we need "real" closures in Java (i.e. mostly better syntax than in my example).

(Of course I'm not answering the question asked; I think what I'm saying is that anonymous classes are good for what I described above. for almost everything else I would create a named inner class because if anything name is self-documenting and is in my opinion easier to read)

薄荷→糖丶微凉 2024-12-27 22:17:16

通常,事件侦听器是一段不太通用的代码,但与特定的小部件、按钮、文本字段等相关。在这种情况下,代码不需要正确公开以供世界重用。在使用它的地方定义它更容易,这就是匿名内部类的用途。它们允许快速将代码片段嵌入到另一个方法中,而不必担心类名、包、可见性或可重用性。

当然,您可以使用匿名内部类执行的操作始终可以使用适当的独立类完成。但是,当您的事件处理类足够通用(可以处理大量事件)、可重用、有状态时,或者更一般地说,当从以下代码中提取事件管理代码有一些好处时,这样做更有意义:定义事件生成元素。

我不确定我具体理解你的问题,我希望这条信息能帮助你找到答案。请随时询问更多问题。

Often, an event listener is a piece of code that is not very generic, but is tied to a specific widget, a button, a text-field, whatever. In such a case, the code does not need to be properly exposed for the world to reuse it. It is easier to define it where it is used, in place, and that's what anonymous inner classes are for. They allow to quickly embed pieces of code inside another method, without having to worry about class names, packages, visibility, or re-usability.

Of course, what you can do with anonymous inner classes can always be done with proper stand-alone classes. But it makes more sense to do it this way when your event handling class is generic enough (can handle lots of events), is reusable, is stateful, or more generally when there is some benefit from extracting the event management code from the code that defines the event-generating element.

I'm not sure I understand specifically your question, I hope this piece of info will help you find your answer. Do not hesitate to ask further questions.

幻梦 2024-12-27 22:17:16

当匿名类实现一种方法和/或占满半个屏幕时,我建议匿名类。

如果匿名者有一段不简单的代码,那么值得拥有一个命名类恕我直言。

I would suggest anonymous classes when it implements one method and/or is half a screen full.

If the anonymous has non trival piece of code its worth having a named class IMHO.

腹黑女流氓 2024-12-27 22:17:16

我的看法:

匿名内部类:从一个函数回调(这样你就不必编写两次代码)

命名内部类:从多个函数回调(或仅用于父类内部逻辑的类)

My take:

Anonymous inner classes: Callback from one function (so you don't write the code twice)

Named inner classes: Callbacks from several functions (or a class that you need only for the internal logic of the parent class)

第几種人 2024-12-27 22:17:16

我仅在匿名内部类包含非常少量的代码时才使用它。原因是我认为它使代码变得混乱并使其可读性降低。

如果需要更多代码,我更喜欢创建一个新类,扩展基类(在本例中为“Doodad()”

I only use an anonymous inner class when it contains a very small amount of code. Reason is IMO it clutters up the code and makes it less readable.

If there is more code required, I prefer to create a new class, extending the base class (in this case 'Doodad()'

红尘作伴 2024-12-27 22:17:16

在您的示例中,您需要创建一个单独的类。这是因为您要覆盖该方法的原因。也就是说,对浏览器事件的处理很差。

具体来说,您可能想在几个不同的地方创建这些改进的小玩意。如果将来更新和改进事件处理会发生什么?您将需要删除所有这些改进的小玩意并使用正确的实现。试图找到所有匿名小玩意可能会很烦人或很棘手。然而,如果您有一个单独的命名类,那么重构该类将很容易。

此外,如果您为 Doodad 创建一个单独的类,那么改进 Doodad 的原因可以是自我记录的。然而,如果您只有一个匿名类,那么您将不得不编写注释或让未来的维护者猜测您为什么要做这些事情。

例如。

public class ImprovedBrowserEventHandlingDoodad extends Doodad {
    ...
}

任何类似于闭包的东西通常都是使用匿名类的良好候选者,

例如。

new Thread(new Runnable() {
    @Override
    public void run() {
        doSomething();
    }
}).start();

您只想在这一组特定的情况下执行某些操作,无需将代码复制并粘贴到其他位置或将其重构为方法。

GUI 的事件处理程序通常使用匿名类,因为它们的使用仅限于 GUI 的设计方式,并且不需要在使用它的特定组件之外创建事件处理程序的单独实例。例如,当您将鼠标悬停在滚动条上时,其外观通常会发生变化。程序中的任何其他内容都不会导致此更改,通常事件处理程序将是几行,告诉滚动条更改其外观,例如。 scrollbar.setMouseOverEffect(true);

In your example you would want to create a separate class. This is because of the reason why you are overriding the method. That is, there is poor handling for browser events.

Specifically, you may want to create these improved Doodads in a couple of different places. And what happens if the event handling is updated and improved in the future? You'll want to remove all of these improved Doodads and use the proper implementation. Trying to find all your anonymous Doodads may be tiresome or tricky. Whereas if you have a separate named class then refactoring out this class will be easy.

In addition the reason for your improving the Doodad can be self documenting if you create a separate class for it. Whereas if you just have an anonymous class then you will have to write comments or leave future maintainers guessing why you've done what you've done.

eg.

public class ImprovedBrowserEventHandlingDoodad extends Doodad {
    ...
}

Anything that resembles a closure is normally a good candidate for using an anonymous class

eg.

new Thread(new Runnable() {
    @Override
    public void run() {
        doSomething();
    }
}).start();

You only want to do something in this one specific set of circumstances and there is no need to copy and paste the code somewhere else or to refactor it into a method.

Event handlers for GUIs are typical in using anonymous classes because their use is limited to the how the GUI is designed and there is no need to create a separate instance of the event handler outside the specific component that is using it. For instance, when you mouse over a scroll bar its appearance generally changes. Nothing else in the program will cause this change and typically the event handler will be a couple of lines telling the scrollbar to change its appearance eg. scrollbar.setMouseOverEffect(true);.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文