Sunday 11 December 2016

Singleton design pattern and preventing its cloning

Singleton :- Singleton design pattern is used to create only single object of the class. we can say to avoid the multiple object creation and limiting the number of objects to one. 

Prevent Object Cloning :- We can prevent the object cloning of singleton class by implementing the Cloneable interface and forcefully throw an exception 'throw new CloneNotSupportedException();' inside overridden clone() methods as written in below example-   

public class MySingletonTest implements Cloneable {

 private static MySingletonTest mSingletonTest = null;

 private MySingletonTest() {

  System.out.println("Sanjaya verma");

 }

 public static MySingletonTest getInstance() {

  if (mSingletonTest == null) {

   mSingletonTest = new MySingletonTest();

  }

  return mSingletonTest;

 }


 @Override
 protected Object clone() throws CloneNotSupportedException {
 // Here forcefully throw an exception to prevent the object cloning

  throw new CloneNotSupportedException();

  //return super.clone();

 }



 public static void main(String[] args) {

  MySingletonTest t1=new MySingletonTest(); 

  try {

       // call to overridden clone method which throw an exception

   MySingletonTest t2=(MySingletonTest)t1.clone(); 
   // compiler will not reach to this line.
   System.out.println(t2); 

  } catch (CloneNotSupportedException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

 }

}



Output-

Sanjaya verma

java.lang.CloneNotSupportedException

 at com.sanjay.java.interview.MySingletonTest.clone(MySingletonTest.java:21)

 at com.sanjay.java.interview.MySingletonTest.main(MySingletonTest.java:30)

No comments:

Post a Comment