Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - circular dependency

I need the view to hold a reference to the contoller because it needs to register the controller as an event listener. I need the contoller to hold a reference to the view, because upon button click, I need to be able to get the selected files in a list. (I have a list of files, and a button 'Add cluster', so when the button is clicked I need to get the selected files)

So in short I have:

Controller controller(view);
View view(controller);

I'm sure there's some bad design here, I just can't figure out how to avoid it..

like image 626
Shmoopy Avatar asked Jun 02 '12 19:06

Shmoopy


2 Answers

I'm not sure what Java Technologies you're using, but in GWT applications -and using MVP pattern- there's no need of the View to have a reference to the Controller: All the communication between the Controller (or Presenter) and the View is made through an interface implemented by the View. In your particular case, your code should look like this:

Define a Display inteface:

public interface Display {
    public void registerEventListener(Listener aListener)
    public List getSelectedFiles ()
}

Let the View implement that interface:

public class View implements Display{
//The method implementations
}

And make all the necessary bindings in the controller:

public class Controller{
    private Display view;
    public Controller(){
        //Or use some DI technology
        this.view = new View();
        //Get a Listener implementation, maybe an Anonymous Inner Class
        this.view.registerEventListener(getListener());
    }

    public void processFiles(){
        List files = view.getSelectedFiles();
        //Do the processing here
    }

}
like image 195
Carlos Gavidia-Calderon Avatar answered Sep 28 '22 19:09

Carlos Gavidia-Calderon


One possible solution:

  • Simply give Controller an addView(View view) method
  • Likewise for View give it an addController(Controller controller) method.
  • Make it part of your documentation that these must be set before use.
  • Make sure you check that the reference variables are not null before using them, since they won't be set in the constructor.
like image 35
Hovercraft Full Of Eels Avatar answered Sep 28 '22 18:09

Hovercraft Full Of Eels