0

オブジェクト指向モデリングとデザインの試験の準備をしていますが、この問題がわかりません。

設計は開閉原則に違反しています。クラスを変更せずに JButton を追加することはできません。これが可能になるように設計をやり直してください。デザインには、3 つのボタンとイベント管理が含まれている必要があります。コードの重複を避けます。クラス図を使用して新しい設計を提示します。

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

1 に答える 1

1

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();
    }
}
于 2015-10-25T16:01:42.473 に答える