One of the most commonly used patterns in graphical applications is the model view controller pattern. In order to make it easy to understand and extend a piece of software, the software needs to have a level modularity that will allow pieces of code to be easily inserted and integrated, without having to rewrite large portions. The model view controller pattern promotes this modularity.
Model view controller separates the a piece of software into three main concerns. These concerns are:
So, back to the scenario we looked at before. If we wanted to print out the kinetic, potential and total energies, we would create a new view. We would only have to write this code once for the simulator and minimiser, since both can use the same view. The models would then tell the views that they have changed, when appropriate, and the views will update accordingly.
But what if we wanted to add more views? Each time we added a view, we would have to write code into the models to tell them to update each view. What if we wanted the model to stop telling the view to update? We'd have to put a conditional statement in our code for each view that would only update the view if wanted it to update. There has to be a better way to do it. This better way is found in the observer pattern.
The observer pattern completely decouples the views from the models. For the purposes of the observer pattern, we will call the models the subjects, and the views, observers. The observers are purely that, they observe a subject, and don't have any impact on the subject. To do this, we need to have a common interface to all the observers, such that the subject can easily notify them all when it has changed.
We also want the observers to be responsible for knowing which subject to look at, and we want the subject to be free of knowing which observers are watching at the time. For this reason, we have two methods in the subject:
With the list of observers, the subject can easily notify all the
observers that it has changed. We add the method notify()
, which
calls a method update()
on each observer. The observers can then
query information from the subject and render it appropriately.