Chapter 8
[ 199 ]
- Concrete state classes: We will have one concrete state class per available
state in the machine. Each state has an event handler method for each event
described in the machine. The state will respond to the event by setting the
context to the next state in the machine. Note that in a Java version of this
pattern, you would also have a State interface class. We don't need this
in Groovy. - Client machine class: This is the client object for the state machine. All client
actions happen via this class. The client class will maintain one state context
object for the current state of the machine, and it will implement an event
handler method for each event in the machine.
Let's start by looking at the state context class. We declare one state property in the
class and set its initial value to the off state:
class StateContext {
def state = new OffState(this)
}
We need one state class for each of the states represented in the machine, so we
implement OffState and OnState classes:
class OffState {
def context
OffState(context) {
this.context = context
}
def toggle() {
context.state = new OnState(context)
}
String toString() {
"OFF"
}
}
class OnState {
def context
OnState(context) {
this.context = context
}