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