Separate Listener class vs. implementing interface vs. Anonymous inner class?

StackOverflow https://stackoverflow.com/questions/22766900

  •  24-06-2023
  •  | 
  •  

質問

What are the benefits/drawbacks of using (Method 1) a separate listener classes (maybe an inner class) like:

private ClassAAL implements ActionListener
{
    ...
}
private ClassAWL implements WindowListener
{
    ...
}

versus (Method 2) implementing the interface

public class ClassA implements ActionListener, WindowListener

versus (Method 3) setting a listener using an Anonymous class for each element that needs a listener.

btn.addActionListener(new ActionListener()...);

Question: What are the Benefits and Drawbacks of each of these methods? Are there performance benefits, or any Design Patterns that recommend one over the other? or any other benefits?

I can see that:

  1. The first method is cleaner
  2. The second method is more compact
  3. The third method adds the listener code right at the element.

Note: I saw a question Nested class vs implements ActionListener on this; but most answers seem to give what the person uses rather than any advantages/disadvantages of each method.

役に立ちましたか?

解決

If you want your listener to be more accessible (API usable), then I would recommend method 2. I also stopped using private classes a few years ago and use public static nested classes:

public class YourClass {

    public static YourNestedClass {
        //...
    }

}

There are no real performance differences in the initialization of them aside from your own implementation. If you make, say, 30 different listener objects for something that could all be done by a common object (as in method 1/2), then there may be a slight difference. Otherwise, you can really just do what you prefer.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top