Thursday 30 January 2014

Avoid cloning Singleton object -Java

HI Viewers
 Here i'm going to give a short note one how to avoid a singleton object from getting cloned.This is one of the interview questions that are being asked frequently while interviewing .We all know that singleton pattern is which doesn't allow for invoking new keyword while creating new instance to that class.generally we achieve it in many ways that i will explain in Singleton design pattern .Here I'm giving you a small code snippet which doesn't allow Singletons instance from getting cloned.

Create a class Singleton and override the Object class clone method and return CloneNotSupported instance to that method
public class Singleton implements Cloneable{
 private static Singleton ss=new Singleton();
 
 private  Singleton() {

 }

 public static Singleton getInstance(){
  return ss;
 }
  public Object clone(){
   
  return new CloneNotSupportedException();
   
  }

}
Now create a sample class to check the Singleton class clone mechanism
public class Example {
public static void main(String args[]){
 
 Singleton ss=(Singleton) Singleton.getInstance().clone();
}
}
Out put: Exception in thread "main" java.lang.ClassCastException: java.lang.CloneNotSupportedException cannot be cast to Singleton

No comments:

Post a Comment