Loading...

Thursday, October 1, 2009

Groovy Goodness: Create a Singleton Class

Creating a singleton class in Groovy is simple. We only have to use the @Singleton transformation annotation and a complete singleton class is generated for us.

package com.mrhaki.blog

// Old style singleton class.
public class StringUtil {
    private static final StringUtil instance = new StringUtil();

    private StringUtil() {
    }

    public static StringUtil getInstance() { 
        return instance;
    }
    
    int count(text) { 
        text.size() 
    }
}

assert 6 == StringUtil.instance.count('mrhaki')

// Use @Singleton to create a valid singleton class.
// We can also use @Singleton(lazy=true) for a lazy loading
// singleton class.
@Singleton 
class Util {
    int count(text) {
        text.size()
    }
}

assert 6 == Util.instance.count("mrhaki")

try {
    new Util()
} catch (e) {
    assert e instanceof RuntimeException
    assert "Can't instantiate singleton com.mrhaki.blog.Util. Use com.mrhaki.blog.Util.instance" == e.message
}

3 comments:

sbglasius said...

I really like all your blog entries. Makes my Groovy knowledge grow every day. Thank you so much!

Anonymous said...

hiho, great blog by the way. im a every day visitor. love reading it.

to the old style:
arent you creating a new class every time you call getInstance? singleton should be there only once

not so sure what effect the private constructor has, mybe that does the trick already.

mrhaki said...

@Anonymous: you are right about the old style, that was wrong. I changed the code in the sample. Thank you for reading the post and noticing the error.

Post a Comment