我正在为面向对象的建模和设计考试做准备,无法解决这个问题。
这种设计违反了开放-封闭原则;如果不修改类,就不能添加更多的JButtons。重做设计,使之成为可能。设计应该包含三个按钮和事件管理。避免重复代码。给出一个类图的新设计。
//other code
private Application application;
private JButton b1, b2, b3;
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
application.action1();
} else if (e.getSource() == b2) {
application.action2();
} else {
application.action3();
}
}
}发布于 2015-10-25 16:01:42
一种方法是将按钮保存在数据结构中。在事件侦听器中,您可以迭代这些项。此外,还可以有一个添加按钮的方法。
示例:
private Application application;
private Map<JButton, Runnable> buttons = new LinkedHashMap<>();
public void addButton(JButton button, Runnable handler){
buttons.put(button, handler);
}
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
// either iterate:
for(Map.Entry<JButton, Runnable> entry : buttons.entrySet()){
if(e.getSource()==entry.getKey()){
entry.getValue().run();
break;
}
}
// or (more efficient) access directly:
Runnable handler = buttons.get(e.getTarget());
if(handler!=null)handler.run();
}
}https://stackoverflow.com/questions/33331555
复制相似问题