Wednesday, July 04, 2012

Singleton Pattern

There are many instances in a project where you will need only one instance to be running. This one instance can be shared across objects. For instance you will only want one instance of database connection object running. Singleton pattern assures that only one instance of the object is running through out the applications life time. Below is the code snippet which shows how we can implement singleton pattern in java.
There are two important steps to be done in order to achieve the same:
  •  Define the constructor as private. That means any external client can not create
    object of the same.
  • Second define the object as static which needs to be exposed by the singleton pattern
    so that only one instance of the object is running.

Example : 
public class clsSingleton
{
public int intcount;
private clsSingleton ()
{
// define the constructor private so that no client can create the //object of this class
}

private static clsSingleton instance = new clsSingleton();

public static clsSingleton getInstance()
{
    return instance;
}
}

As of Java 6 you can singletons with a single-element enum type. This way is currently the best way to implement a singleton in Java 1.6 or later according to tht book ""Effective Java from Joshua Bloch.
package mypackage;

public enum MyEnumSingleton {
 INSTANCE;
 
 // other useful methods here
 
Clearly, we can't create an object of Enum type.
Hence, we can conclude that best way to implement a Singleton pattern is by using Enum.
It is simple, straightforward and unbreakable. 

No comments: