tags:

views:

25

answers:

1

I have a non-MVC Java app that I'm working on refactoring into MVC for future maintainability. The app GUI includes an arbitrary number of rows, each represented by a JPanel containing several controls. I've refactored the logic per row into a model class, and set up a simple controller following the pattern laid out by this java dev center article. I don't want to paste the whole of that code's MVC skeleton, but essentially it assumes there'll only be one View and one Model of each class around, and that each Model will have unique method names. Everything works fine so long as there's only one model and one controller.

Problem: I now have n RowViews, and n RowModels, all added to the controller. When I update any text field in a RowView, all the RowModels are updated. I can see modifying the controller to store a pair of hashes mapping view-to-model and vice-versa, but that seems to violate the principle of thin controllers. I feel like I'm missing something obvious here, design-pattern and strategy-wise. Any thoughts on solving this?

+1  A: 

Your controller should have a datastore (either database or some memory-based map) where a unique identifier indexes each model. Then when you load a model into the controller to modify, you only need modify the "current" model instance.

It sounds like you want a "view partial" when you are displaying multiple models at a time -- the actual "view" would display the table or list of individual model view partials, which could be included in a loop, for (a very simplified) example:

// View
List<Model> modelsToDisplay = controller.someFunctionToLoadModels();
for (Model m : modelsToDisplay) {
    addModelToView(m);
}

...

public void addModelToView(Model m) {
    ViewPartial vp = generateViewPartialForModel(m);
    this.viewPartials.add(vp);
}

...

public ViewPartial generateViewPartialForModel(Model m) {
    ViewPartial vp = new ViewPartial();
    vp.setLabel(m.getName());
    vp.setTextValue(m.getValue());
    return vp;
}
Andy
My coworker pointed out that the model is most often responsible for the datastore and the controller just does the transformation to provide the appropriate model(s) to the view.
Andy