I've always understood MVC to mean the Model shouldn't know anything about the View and vice versa. However in my university course an example of a View using the MVC pattern is given like:
class View implements Updatable {
private final JButton button = new JButton("Press Me!");
private final JTextField textField = new JTextField(10);
//some setup of the button and textfield
public void update(Model model) {
if (model.morePressesAllowed()) {
textField.setText(String.valueOf(model.count()));
} else {
textField.setText("Too Many!");
button.setEnabled(false);
}
}
}
It seems odd to me that the view must know what methods the model has. It seems like it would be better in terms of the MVC pattern to expose the button and textfield to the controller, and have the update method on the controller?
The model just increments a number and if it gets to 5 then the morePressesAllowed returns false.
Also the model has a list of Updatable, and when the counter changes it loops through the updatables and calls update, while this is better than having a list Views, it still seems like the Controller should be responsible for telling the view when the model changes?
EDIT: The model is:
class Model {
private final List<Updatable> views = new ArrayList<Updatable>();
private int count;
private boolean morePressesAllowed = true;
public void addObserver(Updatable observer) {
views.add(observer);
}
public void increment() {
count++;
if (count >= 5) {
morePressesAllowed = false;
}
notifyObservers();
}
private void notifyObservers() {
for (Updatable view : views) {
view.update(this);
}
}
}
The Controller/Main class: (also shouldn't the controller create the model and view and be normal public class?)
public class GuiApp {
private View view = new View(new Controller());
private Model pressCounter = new Model();
class Controller implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
pressCounter.increment();
}
}
GuiApp() {
pressCounter.addObserver(view);
}
}
Also I actually prefer this to something like this: http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm Because in that the controller is just wrapping a bunch of methods of the view and model, which while it seems more MVC like in that the Model and View don't know anything about each other, it just seems less efficient and more complex?