Java – is it possible to shallow copy singleton class objects?

Using the clone method, can we get many instances of a class that has become a singleton?

In addition, is it necessary to write "implements Cloneable" because I know that all objects are extended from the object class, so there should be no access problem for calling the child object of protected clone() on another child node of the object

Solution

It won't happen until you implement clonable with your singleton (this is an anti pattern because it contradicts the purpose of the singleton) So, only when you do this can it happen:

SomeClass. java

class SomeClass implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Singleton. java

class Singleton extends SomeClass {
    public static Singleton instance = new Singleton();
    private Singleton() {}
}

Main. java

class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Singleton singleton1 = Singleton.instance;
        Singleton singleton2 = singleton1.clone();
        System.out.println("singleton1 : "
                       + singleton1.hashCode());
        System.out.println("singleton2 : "
                       + singleton2.hashCode()); 
    }
}

yield

Even in this case, you can solve this problem by overriding clone in singleton and throwing an exception

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>