Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 12

[ 319 ]

The persisted version of the session saved pages as a string so you can see
that the class that represents a page is stored as a string in the saved map. The
restoreSession method creates a newInstance of the page class using reflection.
We also need to generate the default starting page in the TicTacToeEngineSession
constructor. By default, we use the first page as it occurs in the DSL as the start page.
Now, let's look at some of the page classes and event handlers:


class WelcomePage extends PlayerService {
def session

WelcomePage(context) {
this.session = context
setClosureDelegates()
}
def game_start = { Object event ->
players = getPlayers()
page = new PlayersPage(session)
}
def select_players = { Object event ->
}
def play_round = { Object event ->
}
def game_end = { Object event ->
}
def setClosureDelegates() {
if (session) {
game_start.delegate = session
select_players.delegate = session
play_round.delegate = session
play_round.delegate = session
}
}
String toString() {
"welcome"
}
}

There is a notable difference between this class and the state classes we implemented
in the state machine example in Chapter 8, AST Transformations. Here we use closure
instances as the event handler methods. We do this so that the event handler can
have the session object as its delegate.

Free download pdf