Wednesday, 30 May 2007

Singleton pattern implementation in 4 steps

The article describes very simple, fast and efficient way how to create class implementing Singleton design pattern [GoF]. Everything is done in 4 steps using standard features of Eclipse IDE (refactoring and source code manipulation). But it is of course applicable for every IDE providing similar refactoring functionality.

Steps:

  • Create new empty 'SingletonClass' class - use New > Class action from popup menu over package or Ctrl+N shortcut. In the dialog just ensure that the source folder and project are specified and define the name of new class. Press Enter or click OK.
New Class Created
  • From the body of the class invoke Source > Generate Constructors from Superclass... action, of course using Alt+Shift+S, C shortcut. In the following diaglog just press Enter or click OK. (This step can be done together with prvious step checking 'Constructors from superclass' option in the 'New Java Class' dialog).
  • From the constructor signature definition (constructor name) invoke Refactor > Introduce Factory... action (using Alt+Shift+T, O shortcut). In an 'Introduce Factory' dialog change 'Factory method name' value to the name of singleton access method (eg. getInstance). Press Enter or click OK.
  • Select 'new SingletonClass()' from 'getInstance()' method and invoke Refactor > Extract Constant... action (Alt+ Shift + T, A).
  • In a dialog you can change 'Constant name' and visibility but typically the default value is OK. So just press Enter or click OK and voila ....
The result is full-value Singleton design pattern implementation created in 4 very simple steps.

AddThis Feed Button 12 comments:

Adeem basra said...

thats really easy stuff, thanks for sharing

Javarunner said...

This implementation seems suboptimal to me:
a) Why call super() in the constructor? What is the benefit here?
b) How do you extend your singleton class? Can you give an example (i.e. a subclass of SingletonClass) ?

I find it not that much useful generating just a very few lines of code. Besides, you could use a template that already contains getInstance() and the declaration of the static instance attribute.

Roman Bosák said...

TO javarunner:
At the first thank you for your comment.

Ad a) You are absolutely right that explicit call super() in the constructor of the example class realy does not make sense. And much more, with connection to facts from point b (Singleton class has no extensions), it will never make. But still if I will remove the super() explicit call, the compiler will insert it automatically, because default constructor of Object class (Object()) should be called every time the instance is created (see Java Notes - Constructors).

Ad b) Because the singleton design pattern is typicaly used only in cases when you need some util/service class instance (some factory, processor, ...) with only one possible implementation it does not make sense to extend the singleton class. When you need the possibility you can use different design pattern (eg. Abstract Factory or Service Locator)

Mabye you are right that it is not so usefull to generate just a few lines. And also template solution is much more efficient, but it is not applicable when you already have the class implemented and you just want to refactor it to be singleton.
Anyway the purpose of my articles is to show possibilities which Eclipse platform offers to developers (I am leading some of them) and learn them to use the tool efficiently.

Java Donkey said...

Thanks for the post, very good. Maybe you should also describe the value of the singleton pattern if you have time. Also nice blog... I may need to add it to my blog roll as a model.

OJ said...

Surely, if your Singleton class has a private constructor, then it cannot be derived? I would have thought that your constructor would need to be protected so that it can be 'called' from your derived classes when they are constructed

Also, having this as a base class for your singleton objects isn't a sufficient catch-all mechanism because each of those derived classes requires a private or protected constructor. There is no way to enforce that using inheritance.

IMHO, it's better to add the few lines of singleton code to those classes that are singletons rather than trying to abstract it away. Either that, or use generics/templates.

Cheers
OJ

Ricky Clarkson said...

Why don't you make INSTANCE public and get rid of the getInstance() method?

Anonymous said...

To ricky clarkson:

IMHO the reason is the same as why dozens of get*() and set*() methods exist in a lot of classes instead of making the attributes public...

Roman Bosák said...

TO OJ:
If you will try to extend some classes from Singleton class they will not be a singleton anymore. It is because you can not reuse static INSTANCE constant of Singleton class to refer to different types of instances (eg. ExtendedSingleton). It is not bacause it is private (you can change it to protected) but because static reference is owned by class not by instance.

So typical Singleton Design Pattern application looks like you mentioned in third paragraph - every class which instance should be accesible as singleton should implement Singleton Design Pattern by itself.

Roman Bosák said...

TO ricky clarkson:
It is one of good patterns, from my point of view, to use getters in these circumstances. It is because you can change implementation of the getter in the future (eg. some instace pool, ...).

Anonymous said...

Hi Roman,

I have used this construction in the past, (though often by typing I am afraid).
I found out the hard way, that a singleton is not a singleton as you would intuitively understand.

A singleton is only unique per classloader. So, in creating for instance an a set of applets that depend on a singleton will often not work.
As soon as you reference the "singleton" class and the classloader in question did not create the singleton before, it will create a new one, even if the same class instance was created under a different classloader (but maybe the same page).

This will result in multiple singletons.

For that reason I tend to use only stateless singletons or find a different solution.

Guus Bonnema, Leiden, the Netherlands.

Anonymous said...

If you don't want your singleton class to be extended, why don't you declare it as:

public final class SingletonClass{
}

?

Ricky Clarkson said...

You can easily change the code later even if the field is public, thanks to your refactoring IDE.