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.
- 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.
- 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 ....