【发布时间】:2011-07-29 10:38:57
【问题描述】:
可能的重复:
Efficiency of Java “Double Brace Initialization”?
Meaning of new Class(…){{…}} initialization idiom
假设我通过以下方式创建了一个 JMenu Bar:
JMenuItem saveMenuItem = new JMenuItem("Save")
{{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String location = GUI.Custom.QuickDialogs.selectFile(false);
try
{
PrintWriter pw = new PrintWriter(new File(location));
String text = textArea.getText();
pw.println(text);
pw.flush();
pw.close();
}
catch(Exception ex)
{
textArea.append("Could not save this debug output");
}
}
});
}};
JMenu optionsMenu = new JMenu("Options")
{{
add(saveMenuItem);
setVisible(true);
}};
private JMenuBar menuBar = new JMenuBar()
{{
add(optionsMenu);
setVisible(true);
}};
以这种方式创建对象而不是仅声明变量,然后在构造函数中创建对象,这是一种糟糕的设计模式吗?
【问题讨论】:
-
我并不真正担心效率,我更担心这会造成一些极端情况或我遗漏的其他问题。我只是觉得我不经常看到这个是有原因的。