next up previous
Next: How to Write a Up: GUI Programming Previous: Coding the View Class

How to Write a Simple Model

From the perspective of GUI design, the critical issue in developing a model is defining the interface for manipulating the model. This interface should be as transparent as possible, without making a commitment to a particular user interface.

In our click counter example program, the model class is utterly trivial. In accordance with the model-view-controller pattern, it is does not presume any particular user interface. The only feature of the counter targeted at supporting a user interface is the toString method which pads the output String with leading zeroes to produce the specified display width of 3 digits.

class ClickCounter {

  // ** fields **
  private static final int MAXIMUM = 999;
  private static final int MINIMUM = 0;
  private static final int STRING_WIDTH = 3;
  private static int count = MINIMUM;
  
  // ** constructor
  public ClickCounter() {}
  
  // ** methods
  public boolean isAtMinimum() { return count == MINIMUM; }

  public boolean isAtMaximum() { return count == MAXIMUM; }

  public int inc() { 
    if (! this.isAtMaximum()) count++; 
    return count;
  }

  public int dec() { 
    if (! this.isAtMinimum()) count--; 
    return count;
  }

  public void reset() { count = MINIMUM; }

  public int getCount() { return count; }

  // ** toString() **
  public String toString() {

    StringBuffer buffer = 
      new StringBuffer(Integer.toString(count));
    while (buffer.length() < STRING_WIDTH) buffer.insert(0,0);
    return buffer.toString();
  }
}



Corky Cartwright 2004-02-05