Integrating It All
[ 346 ]
Loading the DSL
The transformed DSL classes need to be in the application class path so that the
game engine controller can delegate events to them. For this particular DSL, it
is a requirement that the DSL can be loaded from a source external to the game
server. This is so that the game server, which is not intended to be modified, can be
packaged as an application runtime while the game engine DSL can be maintained in
a separate source.
The DSL classes need to have access to the application class path when loaded.
We also want to minimize the amount of parsing that occurs. This implies creating
a GroovyClassLoader that is shared somehow.
Spring components are, by their nature, singletons. We can create a
GameEngineService class and annotate it with @Component. The classLoader
property in the service is initialized only once. We use getEngineInstance as a
factory method which will parse the DSL and return an engine instance:
@Component
class GameEngineService {
GroovyClassLoader classLoader
def getEngineInstance(obj, engine) {
if (!classLoader) {
classLoader = new GroovyClassLoader(
obj.class.classLoader)
}
def clazz = classLoader.loadedClasses.find {
it.name == "${engine}"
}
if (!clazz) {
clazz = classLoader.parseClass(
new File("engines/${engine}/Engine.groovy"))
}
clazz.newInstance()
}
}
http://www.ebook3000.com