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.

Upcoming Training Events

0 AM
Visual Studio Live! San Diego
September 8-12, 2025
Live! 360 Orlando
November 16-21, 2025
Cloud & Containers Live! Orlando
November 16-21, 2025
Data Platform Live! Orlando
November 16-21, 2025
Visual Studio Live! Orlando
November 16-21, 2025