【问题标题】:Java open closed principle designJava开闭原理设计
【发布时间】:2015-10-25 15:40:27
【问题描述】:

我正在准备面向对象建模和设计的考试,但无法解决这个问题。

设计违反了开闭原则;你不能在不修改类的情况下添加更多的 JButton。重做设计,使之成为可能。设计应包含三个按钮和事件管理。避免重复代码。用类图展示新设计。

//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();
        }
    }
}

【问题讨论】:

  • 为每个按钮使用单独的监听器。
  • 顺便说一句,我认为这不是开闭原则及其违反的一个特别好的例子。

标签: java oop open-closed-principle


【解决方案1】:

一种方法是将按钮保留在数据结构中。 在您的事件侦听器中,您可以遍历这些项目。 此外,您可以有一个添加按钮的方法。

例子:

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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多