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

  1. In the model, select the existing package which you want to create a singleton in.

  2. From the contextual menu (rightclick) execute the module Java Architect → image Patterns → Create singleton command.

  3. The command will pop the following GUI

Singleton Pattern Dialog - Create
  1. Fill the name of the Singleton class to create

  2. Choose the implementation variant: Simple, Synchronized, Static, Holder

  3. Check that the chosen variant suits your needs in the figure drawn in the dialog.

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

  1. In the model, select the existing class which you want to become a singleton

  2. From the contextual menu (rightclick) execute the module Java Architect → image Patterns → Transform into singleton command.

  3. The command will pop the following GUI

Singleton Pattern Dialog - Transform
  1. Choose the implementation variant: Simple, Synchronized, Static, Holder

  2. Check that the chosen variant suits your needs in the figure drawn in the dialog

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