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

introadvantagesexample appherecontrollersviewstodosrefs

the heartbeat model

Our model of the heart (source) will be a pretty simple loop :

public void run() {

  while (running) {



    try {

      Thread.sleep(SLEEP_DURATION * excitementLevel);

    } catch (InterruptedException e) {

      // do nothing if interrupted




Each time through the loop, we increment the number of beats, and continue to loop until running is false. running is a boolean flag to represent the state of the model. The method stopHeart that is used to set running to false. Unfortunately, the heart cannot be restarted.

public void stopHeart() {

  running = false;


Likewise, the model provides a method for adjusting the excitementLevel - adjustExcitementLevel which adds the amount passed in to it to the current excitementLevel.

public void adjustExcitementLevel(long delta) {

  excitementLevel += delta;

  if (excitementLevel < 1) {

    excitementLevel = 1;



These are the only methods available to the controller objects. These methods define the model's API and there are no other ways of altering the model's state.

The views are updated via the updateObservers method. It calls the setChanged method within the Observable class, then uses the Observable class's notifyObservers method passing an Integer object containing the value of the current heart beat. The notifyObservers will call the update method in each of the registered Observer objects.

Let's look closely at the controller object now.

introadvantagesexample appherecontrollersviewstodosrefs