Java Reference
In-Depth Information
4.4.3. Creating singletons
When a new Java developer first discovers the wide, wonderful world of design patterns,
one of the first ones they tend to encounter is Singleton. It's an easy pattern to learn, be-
cause it's easy to implement and only involves a single class. If you only want one instance
of a class, make the constructor private, add a static final instance variable of the
class type, and add a static getter method to retrieve it. How cool is that?
Unfortunately, our poor new developer has wandered into a vast jungle, full of monsters
to attack the unwary. First of all, implementing a true singleton isn't nearly as easy as it
sounds. If nothing else, there are thread safety issues to worry about, and because it seems
no Java program is every truly thread-safe the results get ugly fast.
Then there's the fact that a small but very vocal contingent of developers view the whole
Singleton design pattern as an anti-pattern. They trash it for a variety of reasons, and they
tend to be harsh in their contempt for both the pattern and anyone foolish or naïve enough
to use it.
Fortunately I'm not here to resolve that issue. My job is to show you how Groovy can help
you as a Java developer, and I can do that here. As you may have anticipated based on the
title of this section, there's an AST transformation called @ Singleton .
To use it all I have to do is add the annotation to my class. Here I've added it to the Im-
mutablePointFactory from earlier:
@Singleton
class ImmutablePointFactory {
ImmutablePoint newImmutablePoint(xval,yval) {
return new ImmutablePoint(x:xval,y:yval)
}
}
Again,Ican'tresist sayingit: that waseasy.Theresult isthat theclass nowcontains astatic
property called instance , which contains, naturally enough, the one and only instance
of the class. Also, everything is implemented in as correct a manner as possible by the au-
thor [ 10 ] of the transformation. In Groovy code I can now write the following:
Search WWH ::




Custom Search