Pages

Tuesday, July 31, 2007

A Case for Groovy Singleton

In my last post I've written about the new feature in Groovy API, the GroovySystem class. Now I would like to give it a try for the singleton pattern implementation inside the plug-in extension.

Why would I ever want to do that? The singleton class could be used for persisting the state between the same action calls. I wanted to try this solution just because it must be possible to implement the same thing in the different ways. Nothing else.

Here's an example:

def expando = new groovy.util.Expando()

class MySingleton {
String toString() { 'MySingleton: ' + hashCode()}
}

class MySingletonMetaClass extends MetaClassImpl {
private final static INSTANCE = new MySingleton()
MySingletonMetaClass() { super(MySingleton) }
def invokeConstructor(Object[] arguments) { return INSTANCE }
}

def registry = GroovySystem.metaClassRegistry
registry.setMetaClass(MySingleton, new MySingletonMetaClass())

expando.run = {action ->
expando.workbenchWindow.getActivePage().
showView("org.eclipse.soc.yummy.views.ScriptView")
println "hello groovy action: ${action}"
def single = new MySingleton()
println "${single}"
}

I just create a singleton using the GroovySystem and MetaClassImpl, so that when an action delegate gets called, I will have always the same instance of the singleton class.

Unfortunately, I didn't find a way to implement the same in case of different scripts, e.g. if I have two different scripting extensions. Perhaps I will have to provide a single class to the plug-in which could be used just for this purpose.

No comments:

Disqus for Code Impossible