[英]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.