Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Tuesday, May 29, 2012

Singleton Pattern in JAVA

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;
}
}