cristobal baray
kids iPhone apps
s100+ pages

Last edited - March / 99
-- Hear and forget; see and remember; do and understand...

the model-view-controller (MVC) design pattern


MVC toy example

Since I found the MVC pattern easier to understand once I had an example to hack around with, I'll present a toy example here. It is a little heartbeat monitor application. The model will model the heart whose only significant events are beats, the view will display a count of the heartbeats, and the controller will allow one to either excite (speed up) or bore (slow down) the model heart.

In most cases, I prefer leaving the views and controllers in separate Java windows. This makes it easier for me to work with them - also, I can add and subtract them from the application easily. In some cases it is more appropriate to allow the user to interactively control which views to display. Only when there are strong pressures to integrate the view and controller into one window will I do it. Also, this design makes it easy for me to wrap up my Java applications into applets, like this one :

The applet only contains a start-button, which then goes and executes the main method within the application class. I put the main method within the applet class, so that the same class can be used to start the applet or application up. A more general "start button" can be created that would take a parameter from the web page the applet is on, which would name the class containing the main method. This I believe is what they used in Sun's tutorial somewhere, but I can't find a direct reference to it.

I also took advantage of the applet's sound playing capabilities. I made the applet into yet another view, but this one doesn't display the data visually. Instead, this view will play a sound (I tried to find a beep to make it EKG-ish, but the best I could do is a click...).

After trying out the applet, it should be obvious that the program's pretty simple. There's a loop that simulates the heart beats, which sleeps for some duration. The user can affect this duration via the "excite" or "bore" buttons that appear in a separate window. There is also a sound played each time the heart beats and in another window, the total number of heart beats so far is displayed.

From using the applet, we can see the needs of each object :

  • the model needs to present other objects a way of adjusting the delay and stopping the heart beat outright. It also notifies the views when heart beat events occur.
  • the controller needs to allow the user to adjust the heartbeat rate and a way of stopping the beat as well.
  • the views need to know when a heart beat happens - and possibly the number of heart beats the heart model has simulated.

Each of these points will be discussed more thoroughly as we cover each object..starting with the model.