Cilla
Cilla

Reputation: 429

Java MVC architecture

I'm developing an email client/server java application with RMI. I designed client based on MVC architecture. In particular, I've registered the Controller as a View event listener so that, for example, if I press the "inbox" button of the View, the Controller can download incoming emails from the server through a stub of the server itself.

The consequence of all this is that the controller is full of conditional code blocks on the name of the button pressed, which is very bad. Can anyone recommend me a way for replace conditional blocks? I thought about using some design patterns but I'd not know which is the best in this case.

Thanks!!

Upvotes: 2

Views: 245

Answers (2)

René Link
René Link

Reputation: 51473

Instead of writing if/else statements

public class Controller implements ActionListener {

    public void actionPerformed(ActionEvent ae){
        if(....) {
           // action1
        } else if(...){
           // action2      
        }
    }
}

put every branch in an own method. E.g.

public class Controller {

    public void action1(){
        // ....
    }

    public void action2(ActionEvent ae){
        // ....
    }
}

Now you can use an anonymous ActionListener to delegate to the right method. E.g.

btn1.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent ae){
       controller.action1();
   }
});

btn2.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent ae){
       controller.action2(ae);
   }
});

With Java 8 you can use method references or lambda expressions.

Controller controller = new Controller();

btn1.addActionListener(controller::action1);
btn2.addActionListener(ae -> controller.action2());

Upvotes: 2

A. Shevchuk
A. Shevchuk

Reputation: 2169

Let's imagine you have 2 buttons on your view, let them be "Send" and "Close" I think it's better to have two methods inside of controller, like controller.onCloseClicked() and controller.onSendClicked().This way you can use two options:

  1. implement one listener and add conditional code blocks to decide what method of controller to fire.
  2. implement few listeners for buttons, one for each button and fire concrete method of contoller directly from them.

Why it's better? Sometimes you need to send not only event, but some bundle of data from ui(view) to controller. When you have one method per action it's easier to handle.

Upvotes: 1

Related Questions