next up previous
Next: 3.1.4 How to Write Up: 3.1 GUI Programming Previous: 3.1.2.0.2 Coding the View

3.1.3 How to Write a Trivial Model

The model class for this program is utterly trivial. In accordance with the model-view-controller pattern, it is designed in complete independence from the particular user interface. The only feature that of the counter targeted at supporting the 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
2000-01-07