tucuxi
tucuxi

Reputation: 17955

Access to Model in a Java Model-View-Controller design

I am developing an editor following the general MVC design: the model holds the data, the controller knows how to change it, and the view issues calls the controller to query and modify the model. For the sake of argument, let us use

public class Model {
    public Object getStuff(String id);
    public void setStuff(String id, Object value);    
}    

public interface Controller {
    public void execute(Command command);
    public void redo();
    public void undo();     
    public void save();
    public void load(File f);
}

The class that actually implements the controller holds a reference to the model; commands need to access it too, so they must all provide a void execute(Model m); interface that actually grants them this access only when needed.

However, views generally need access to the model - when building themselves and, later on, to listen for changes and refresh themselves accordingly. I am afraid that adding a "Model getModel()" call to the Controller will result in a great temptation to bypass the execute() mechanism; and I am not the only developer working on the project. Given this scenario, how would you enforce an "all changes go through the controller" policy?

Two alternatives I am considering:

Upvotes: 4

Views: 2393

Answers (2)

user1538812
user1538812

Reputation:

What if you take a look at Observer Pattern http://en.wikipedia.org/wiki/Observer_pattern, your view only listen for events from model. Hope it helps.

Upvotes: 0

Chris Gerken
Chris Gerken

Reputation: 16400

I recommend modeling the access to the model as a set of classes. For example, if the view needs to modify a customer's attributes, there would be a ModifyCustomerCommand class that would have as properties all of the information needed in order to perform the update. The view would construct an instance of the class with values and pass it back to the controller which, in turn, would pass the command back to the model for the actual update.

A benefit from this approach is that each of these model access commands can implement undo behavior. If the controller keeps an ordered collection of these commands as they get sent back to the model, the controller can back off the changes, one at a time, by invoking the undo method on the most recently executed command.

Upvotes: 1

Related Questions