Wednesday, November 16, 2011

Singleton


The Singleton is a useful Design Pattern for allowing only one instance of your class.

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

Below are the example for singleton..

Case 1:

public class Singleton {

private static Singleton singleton;

private Singleton(){
}

public static synchronized Singleton getInstance(){
if(singleton==null)
singleton = new Singleton();
return singleton;
}

}

Case 2:

public class Singleton {


private static Singleton singleton = new Singleton();

private Singleton(){
}

public static synchronized Singleton getInstance(){
return singleton;
}
}


The difference between Case 1 and Case 2 is that in Case 2 singleton is instantiated when the class is loaded, while in the Case 1, it is not instantiated until it is actually needed.

No comments:

Post a Comment