Search code examples
javaoopopen-closed-principle

Java open closed principle design


I am preparing for exam in object oriented modelling and design and can't figure out this problem.

The design is in violation of open-closed principle; you can't add more JButtons without modifying the class. Redo the design so that this becomes possible. The design should contain the three buttons and the event management. Avoid duplicated code. Present the new design with a class diagram.

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

Solution

  • One way would be to keep the buttons in a Data structure. In your event listener, you could then iterate through the items. Also, you could have a method that adds buttons.

    Example:

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