Saturday, September 13, 2008

What is a Singleton Pattern

Singleton pattern is used to ensure there is one and only one instance of a class.

There are three parts to it

A. Ensure that we cant have more than one instance of the class
This is done by marking the constructor as private or protected
B. Provide a mechanism to access the singleton object. This is typically done by providing a static method to access the object. Something like getInstance ()method
C. Creation of the object.
This is by far the most tricky part.There are many ways to do so
1) Create the object using the static initializer or Construct the object at the time of declaration
This uses the classloader to create the object. You can run into issues in a J2EE environment where there can be multiple classloader
2) Use an inner static class. The singleton object is held in a static inner class. This will ensure that the object is not created until its really needed
3) Use double-checking mechanism. This means that we create the object in the getInsatnce() method- we check for NULL before creating the object. And the call to the creation of the object is enclosed withing synchronized block

No comments: