Chapter 8
[ 217 ]
methodStatement = new ExpressionStatement(
new BinaryExpression(
new PropertyExpression(
new VariableExpression("context"),
new ConstantExpression("state")
),
new Token(Types.EQUALS, "=", -1, -1),
new ConstructorCallExpression(
ClassHelper.make("$nextState$className"),
new ArgumentListExpression(
new VariableExpression('context')
)
),
)
)
}
def eventMethodNode = new MethodNode(
"${event}",
Modifier.PUBLIC,
null,
new Parameter[0],
null,
methodStatement
)
stateClassNode[1].addMethod(eventMethodNode)
}
The expression we need to add to an event method for a state transition must set the
state property of the context class to the next state. So, for instance, the toggle event
of an OFFState needs to be context.state = new ONState(context). We build
an AST structure as follows:
MethodNode toggle()
|_ExpressionStatement (expr)
|_BinaryExpression (expr) = (expr)
|_PropertyExpression (context).(state)
| |_VariableExpression context
| |_ConstantExpression state
|_Token =
|_ConstructorCallExpression new ONState
|_ArgumentListExpression context