[英]Nested class vs implements ActionListener
创建实现ActionListener的嵌套类是否有任何优点或缺点:
public class Foo{
Foo(){
something.addActionListener(new ButtonListener());
}
//...
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//...
}
}
}
与在主类本身中实现ActionListener相比:
public class Foo implements ActionListener{
Foo(){
something.addActionListener(this);
}
//...
public void actionPerformed(ActionEvent e){
//...
}
}
我经常看到两个示例,并且只想知道是否存在“最佳实践”。
@Ankur,您仍然可以使用匿名内部类作为您的侦听器,并具有独立的独立控制类,因此具有可维护的代码,这是我喜欢使用的一种技术。 例如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnonymousInnerEg {
private static void createAndShowUI() {
GuiPanel guiPanel = new GuiPanel();
GuiControl guiControl = new GuiControl();
guiPanel.setGuiControl(guiControl);
JFrame frame = new JFrame("AnonymousInnerEg");
frame.getContentPane().add(guiPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class GuiPanel extends JPanel {
private GuiControl control;
public GuiPanel() {
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (control != null) {
control.startButtonActionPerformed(e);
}
}
});
JButton endButton = new JButton("End");
endButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (control != null) {
control.endButtonActionPerformed(e);
}
}
});
add(startButton);
add(endButton);
}
public void setGuiControl(GuiControl control) {
this.control = control;
}
}
class GuiControl {
public void startButtonActionPerformed(ActionEvent ae) {
System.out.println("start button pushed");
}
public void endButtonActionPerformed(ActionEvent ae) {
System.out.println("end button pushed");
}
}
我认为第一种方法更好,因为您的类将具有单独的代码来处理操作。 通常,组合也比继承更好,因此,一个类只有在确实是一个超类型时才应该扩展一个类或实现一个接口。
同样出于可维护性,我们说Foo类对侦听另一种不同类型的事件然后执行操作有新的要求,在这种情况下,头等类也可以轻松修改。
如果我不担心可维护性,我宁愿参加匿名课程。
如果Foo类除封装此按钮外没有其他责任,则第一种解决方案是可以的。
但是,一旦Foo得到更多必须听的“东西”,它就会变得混乱。 我更喜欢第二种解决方案,因为它更明确,并且具有更好的可伸缩性。
更好的解决方案可能是创建一个统一的内部类。
public class Foo{
Foo(){
something.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//...
}
});
}
}
通常,您想使用嵌套的甚至是匿名的类,而不是将ActionListener暴露给封闭类的API。 (公共类Foo实现了ActionListener-> Javadoc将声明Foo是一个ActionListener,尽管这通常只是一个实现细节->错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.