Search code examples
javamodel-view-controllerviewcontrollercommunication

Implementation of MVC View and Controller communication. (Java)


In my class we have been learning about different designs such as MVC and MVP. I am currently writing an application that displays data in a JTable and a custom plot. My question is how should I go about communicating between the View and Controller.

As an example, I have a button that should import data from a file into the Model. What I think I want is the View to notify the controller that the user wants to import a file. The controller then does the necessary logic to do so. How should the view do so? I see a couple of options. 1) Have the controller create an innerclass that gets called whenever a user hits the import button. In this case the controller would have to call a method of the view to see what file the user wanted to import. 2) Have the view detect the event and then call an appropriate method in the controller passing with it the name of the file.

This begs the bigger question of whether or not the view knows about the controller? I know there isn't a correct answer to these things but what would be the best way?


Solution

  • As you may know, the Controller layer is, most of the time, tightly coupled to the View layer.

    In the projects I participate as a architect or programmer, I never put business logic in a controller. Because I never saw any technology in which the layer that communicates directly to the view can be ported.

    The controller layer should act as a service layer to the view. So yes. The view must know about the controller. And, if the previous statement is true, there's no problem the controller could communicate with the view.

    I design my business logics (my @EJB or spring's @Service) in a completely POJO-based layer. That's my portable business layer.

    The controller is just a bridge between the view and the business rules layer. It calls business methods, format their responses properly (sometimes) and send back to the view. In this context, the controller can be a web service, a managed bean, a test suite, etc...