Singleton is a design pattern that ensures that a class has only one instance and provides a unique global access point to this instance.
Applying the Singleton pattern
You can either:
-
create a brand new Singleton class and therefore add a class to your model
-
transform an existing class into a Singleton implementation and therefore modify the existing class.
Creating a new Singleton class
-
In the model, select the existing package which you want to create a singleton in.
-
From the contextual menu (rightclick) execute the
Java Architect →
Patterns → Create singleton command.
-
The command will pop the following GUI

-
Fill the name of the Singleton class to create
-
Choose the implementation variant: Simple, Synchronized, Static, Holder
-
Check that the chosen variant suits your needs in the figure drawn in the dialog.
-
Press the OK button to apply the pattern and create the singleton class in the model under the selected package.
Transforming an existing class into a singleton
-
In the model, select the existing class which you want to become a singleton
-
From the contextual menu (rightclick) execute the
Java Architect →
Patterns → Transform into singleton command.
-
The command will pop the following GUI

-
Choose the implementation variant: Simple, Synchronized, Static, Holder
-
Check that the chosen variant suits your needs in the figure drawn in the dialog
-
Press the OK button to apply the pattern and modify the model in order to make of the initially selected class a singleton implementation.
Singleton variants
Variant | Implementation properties |
---|---|
Simple |
Basic implementation, lazy initialization. Not thread safe. |
Synchronized |
Thread safe implementation using a synchronized access to the getInstance() method. |
Static |
Thread safe implementation using a statically initialized attribute. |
Holder |
Thread safe implementation, lazy initialization using a Holder subclass for the instance. |