Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

How do you prevent for creating another instance of Singleton using clone() method in java?

user-image
Question ajoutée par Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date de publication: 2014/04/23

The class will need to implement the clone() mehod as below:

 

public class Singleton {

 

    private static final Singleton singleton = new Singleton();

    private Singleton() { }

    public static Singleton getInstance(){

        return singleton;

    }

    @Override

    protected Object clone() throws CloneNotSupportedException {

        throw new CloneNotSupportedException("Cloning of this class is not allowed"); 

    }

}

Maria Thomas
par Maria Thomas , Tech Lead , J P Morgan Chase

If your class which is based on the Singleton pattern does not implement the Cloneable interface then the clone() method cannot be called on that object. 

More Questions Like This