Tuesday, September 23, 2014

Singleton Pattern

Singleton Pattern

Ensures a class has only one instance, and provides a global point of access to it.




Lazy initialization

Use lazy initialization when you want a Singleton instance to be created on demand. 
This way you are not creating an instance (say if the instance creation logic is time consuming) if it is not needed.

Lazy Initialization + multi-threaded scenarios

Approach 1

Use the following if getInstance() method isn't causing substantial overhead for the application.
So, if a high traffic part of the code begins using getInstance(), you may reconsider, and use approach 2.
Synchronizing a method can decrease performance by a factor of 100.


Approach 2 

Use "double-checked locking" to reduce the use of synchronization in getInstance()



Eager initialization

If the application always uses a Singleton instance, you can create the singleton instance eagerly.
This is also thread-safe.


No comments:

Post a Comment