I have almost completely understood the MVC pattern, but there is one thing that still confuses me:
Let's say - for the purpose of this example - I have got a controller, a model and 5 views. Whenever the model changes, I would like to (optimally) change a (proper) subset of these 5 views as a result of changes in the model.
What would be the right way to do it ?
My understanding of MVC as of now is that the model should not know anything about either controller or view. Does that apply to the view as well ? I.e. does the view also not know about controller AND model ?
Based on the assumption above, the proposal for my MVC program with the given requirements would structurally look something like this:
Pseudocode:
OPTION 1
MODEL
//Random data, no references to either controller or view
notifyObserver(){
observer.modelChanged();
}
CONTROLLER
reference MODEL
reference VIEW
var model;
var view1;
var view2;
var view3;
var view4;
var view5;
createController(m,v1,...,v5){
model = m;
view1 = v1;
.
.
.
view5 = v5;
}
modelChanged(){
view1.updateView(model.someVariable);
view4.updateView(model.someVariable);
}
VIEW
//no references to either model or controller
//some visual elements
updateView(var someVariable){
myVisualElement.change(someVariable);
}
TESTCLASS
main(){
create view1;
create view2;
.
.
.
create view5;
create model;
create controller(model,view1,...view5);
model add observer(controller);
}
So what I am basically doing with this, is letting the controller know about everything, while both view and model act completely independently. In this case, the CONTROLLER
is the only one who gets notified when something changes in the model. It will then go ahead and change its views accordingly.
OPTION 2
So the VIEW
would basically have a property/variable called model
, that I will pass in with the constructor like this:
TESTCLASS
main(){
create model;
create view1(model);
create view2(model);
.
.
.
create view5(model);
create controller(model);
model add observer(view1);
.
.
.
model add observer(view5);
}
This way, all the views have references to the model and are notified by the model as soon as something changes. I am confused because I am not sure which is the right approach... I hope you can help me understand this once and for all.