Singleton

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

 @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }

}
Case 2:
public class Singleton {


 private static Singleton singleton = new Singleton();
 private Singleton(){
 }
 public static synchronized Singleton getInstance(){
  return singleton; 
 }
 
 @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }
}
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.

It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...