Loading sub-menu...

Singleton Pattern

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Singleton Code Example

Thread safety warning!

As shown above, the singleton is not thread safe. Used properly, singletons can be beneficial. Some people believe they are just evil. There are two camps, as usual. An alternative to the Singleton pattern is using a factory class to manage singletons. In other words, inside of a factory class, you can ensure that one and only one object is created.

If you are thinking about implementing this pattern, please review the following article first:

Singletons with needles and thread - Two approaches to creating thread-safe singletons

Singletons with Spring Beans

With the Spring dependency injection and inversion of control (IoC), handling singletons is much easier. Simply define your bean in your bean configuration file (e.g. applicationContext.xml) with singleton="true". Spring will ensure that only one instance of the class is ever instantiated. For example:



Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.