Monday, March 09, 2009

Various Methods of Implementing Singleton:

public class Singleton {
/*
*
* Type 1
*
* Advantages : Best of all the implementations available
* Thread safe
* Works on all version of jvm
*
*
protected Singleton(){
System.out.println("Singleton Contructor Called...");
}
private static class SingletonHolder{
private final static Singleton singleton = new Singleton();
}//End of class SingletonHolder
public static Singleton getInstance(){
return SingletonHolder.singleton;
}
*/

/*
*
* Type 2
*
* Advantage : Very basic singleton pattern .
* Works on all JDK Version
*
* Disadvantages : Not a thread safe
*
private Singleton(){}
private static Singleton singleton = null;
public Singleton getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
*/
/*
*
* Type 3
* Advantages : Thread Safe algorithm
* Disadvantages : Blocks to acquire a lock
*
*
private static Singleton singleton = null;
private Singleton(){};
public Singleton getInstance(){
if(singleton==null){
synchronized(Singleton.class){
singleton = new Singleton();
}//End of synchronized block
}//End of if
return singleton;
}
*/
/*
*
* Type 4
*
*Advantages : No Synchronized blocks and hence no locking
* Readily available . *Disadvantages : Not a lazy loaded singleton.
*
*

private static Singleton singleton = null;
static {
singleton = new Singleton();
}
private Singleton(){};
public Singleton getInstance(){
return singleton;
}
*/

}//End of class Singleton

0 Comments:

Post a Comment

<< Home