How to prevent Cloning to break a Singleton Class Pattern in Java?

Java 8Object Oriented ProgrammingProgramming

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −

Example - Breaking Singleton

Live Demo

public class Tester{
   public static void main(String[] args) 
      throws CloneNotSupportedException { 
      A a = A.getInstance();
      A b = (A)a.clone();

      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }
}

class A implements Cloneable {
   private static A a; 
   private A(){}

   public static A getInstance(){
      if(a == null){
         a = new A(); 
      }
      return a;
   } 

   @Override
   protected Object clone() 
      throws CloneNotSupportedException {
      return super.clone();
   }
}

Output

705927765
366712642

Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −

Return the same object in the clone method as well.

Example - Protecting Singleton

@Override
protected Object clone() 
throws CloneNotSupportedException {
   return getInstance();
}

Output

705927765
705927765
raja
Published on 03-Dec-2018 15:09:31
Advertisements