## Sigleton pattern

### Introduction

Ensure a class only has one instance, and provide a global point of access to it.

### Participants:

#### Singleton

- a class, which should be instantiated only once
- this participant can not be an interface.

#### Singleton Factory

- a class with a static method to instantiate Singleton
- this participant can not be read-only.
- this participant can not be an interface.

### Note:

The Singleton and Singleton Factory could be the same class. In this case, it will contain a static method to instantiate itself only once.

In the "Unique instance attribute" you can specify the name of an attribute where Singleton Factory will keep a reference to the (only) instance of Factory.

In the "Instance method" field you can specify the name of a method for obtaining the Singleton object.

If "Generate thread-safe code" option is checked the singleton class will ensure its correct behavior in multithreaded environment by using the `synchronized` block in the "Instance method".

The "Create pattern links" option controls whether to generate additional links which can be used by this pattern later to determine classes and interfaces participating in the pattern. That means that if you selected this option and used the pattern to create a set of classes and interfaces, the pattern invoked for some participant later (via the popup menu item "Choose Pattern...") will automatically find (if it is possible) all other participants and fill in participant fields with their names.

Also, if you applied the pattern with this option on and invoked the pattern via the popup menu item "Choose Pattern..." for some participant later, the pattern will have additional field called "Use selected class as", containing possible roles for the selected element.

This option is very useful when you are planning to change something in the classes/interfaces participating in the pattern. For example, if this option is on and after creation of the classes and interfaces you added several methods to certain interface-participant (and this change must be reflected somehow in other participants), all you have to do is to select this changed interface, invoke the "Choose Pattern..." dialog for this element and select the original pattern. After that the pattern will determine other participants and you will only have to press "Finish". The pattern will modify all other classes and interfaces accordingly to your changes.

### Applicability

Use the Singleton pattern when

- there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
- when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.