【发布时间】:2018-12-13 12:10:57
【问题描述】:
考虑一个类
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ShortcutButton extends JButton {
public ShortcutButton(String text, KeyStroke[] keyStrokes, ActionListener actionListener) {
super(text);
addActionListener(actionListener);
addShortcut(keyStrokes);
}
public ShortcutButton(String text, KeyStroke keyStrokes, ActionListener actionListener) {
super(text);
addActionListener(actionListener);
addShortcut(keyStrokes);
}
public ShortcutButton(String text, String[] keyStrokes, ActionListener actionListener) {
super(text);
addActionListener(actionListener);
addShortcut(keyStrokes);
}
public ShortcutButton(String text, String keyStrokes, ActionListener actionListener) {
super(text);
addActionListener(actionListener);
addShortcut(keyStrokes);
}
public void addShortcuts(KeyStroke[] keyStrokes) {
for (KeyStroke keyStroke : keyStrokes) {
addShortcut(keyStroke);
}
}
public void addShortcuts(String[] keyStrokes) {
for (String keyStroke : keyStrokes) {
addShortcut(keyStroke);
}
}
public void addShortcut(String keyStroke) {
addShortcut(KeyStroke.getKeyStroke(keyStroke));
}
public void addShortcut(KeyStroke keyStroke) {
//some code here
}
}
如您所见,ShortcutButton() 构造函数和addShortcuts() 函数具有不同的签名,但主体相同。有没有一种很好的方法可以缩短这段代码,以免在四个不同的函数中复制粘贴相同的代码?
【问题讨论】:
-
也许你能做的最重要的事情就是删除代码。反复进行“有用的”重载是没有帮助的。 (也“更喜欢组合而不是继承”(或静态方法而不是继承),但这在 GUI 编程中似乎是一个失败的原因。)
标签: java overloading constructor-overloading