Wednesday, May 18, 2011

Java Singleton Design pattern

A class which must create only one object (ie. One instance) irrespective of any number of object creations based on that class.

Steps to develop single ton class:- 
1.Create a Private construcor, so that outside class can not access this constructor. And declare a private static reference of same class
2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

Sample Code:-


public class SingleTonExample

{
private static SingleTonExample st=null;
private SingleTonExample()
{
System.out.println(“\nIn constructor”);
}
public static SingleTonExample getInstance()
{
if(st==null)
st=new SingleTonExample();
return st;
}
}

How to use the Singleton class created above is described in below class:

public class UsingSingletonClass{
             public void testMethod(){
               SingleTonExample st = SingleTonExample.hetInstance();
               //you can use the SingleTonExample object st for your requirements
}

}

No comments: