PATTERNS IN JAVAMatters of state
- By Kevlin Henney
- May 13, 2000
PATTERNS IN JAVA
Matters of state
Kevlin Henney
Listing 3. Implementation of the clock's life cycle using a Stateless Object for the mode.
public class Clock
{
public synchronized void changeMode()
{ mode.changeMode(this); }
public synchronized void increment()
{ mode.increment(this); }
public synchronized void cancel()
{ mode.cancel(this); }
private interface Mode
{
void changeMode(Clock context);
void increment(Clock context);
void cancel(Clock context);
}
private static class DisplayingTime implements Mode ...
private static abstract class SettingTime implements Mode
...
private static class SettingHours extends SettingTime ...
private static class SettingMinutes extends SettingTime
{
public void changeMode(Clock context)
{ context.mode = displayingTime; }
public void increment(Clock context)
{ ++context.minutes; }
}
private int hours, minutes;
private Mode mode = settingHours;
private static final Mode
displayingTime = new DisplayingTime(),
settingHours = new SettingHours(),
settingMinutes = new SettingMinutes();
}
About the Author
Kevlin Henney is a Principal Technologist with QA Training in the UK.