This template can be used to automatically add all the singleton code to your class. To add it do the following:
First goto Window->Preferences and then on the left side go to Java->Editor->Templates. Now click on New and fill in the following information:
| Field |
Value |
description |
| Name |
singleton |
When typing 'singleton' in your code press CTRL + SPACE to select the template |
| Description |
Singleton design pattern |
|
| Context |
java |
|
And copy the following code into the Pattern field:
/**
* Instance variable containing the singelton reference.
*/
private static ${enclosing_type} instance = null;
/**
* Private constructor so that this object cannot be instantiated.
*/
private ${enclosing_type}() {
// Initialization code goes here.
}
/**
* Method for retrieving the singleton instance of the <code>${enclosing_type}</code> class.
*
* @return a reference to the singleton instance.
*/
public static synchronized ${enclosing_type} getInstance() {
if (instance == null) {
instance = new ${enclosing_type}();
}
return instance;
}
${cursor}
/**
* Disable cloning since this is not supported for singleton classes.
*/
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Now press OK and the template is stored.
To use the template do the following, create a new class without any
code, go with the cursor inside the class and type 'singleton', now
press CTRL + SPACE and select the 'singleton' template. Now you should
have all the code for the singleton.
|