PATTERNS IN JAVAMatters of state

PATTERNS IN JAVA
Matters of state

Kevlin Henney

Listing 1. Implementation of the clock's life cycle using a flag and explicit switching.


public class Clock
{
  public synchronized void changeMode() ...
  public synchronized void increment()
  {
    switch(mode)
    {
    case displayingTime:
      throw new Exception("Change mode to change time");
      break;
    case settingHours:
      ++hours;
      break;
    case settingMinutes:
      ++minutes;
      break;
    }
  }
  public synchronized void cancel() ...
  ...
  private static final int displayingTime   = 0;
  private static final int settingHours     = 1;
  private static final int settingMinutes   = 2;
  private int hours, minutes;
  private int mode = settingHours;
}

About the Author

Kevlin Henney is a Principal Technologist with QA Training in the UK.