vendredi 21 juin 2019

Difficulty understanding why subclassing singleton contradicts definition of singleton?

From other answers on here, I see that essentially subclassing a singleton contradicts what it means to have a singleton. However, I don't quite understand why each subclass can really crea

class Singleton {
    private static Singleton instance = null;
    protected Singleton() {

    }
    public static Singleton getInstance(){
        if (instance == null) {
            instance = new Singleton();         
        } 
        return instance;
    }
}

class SubclassSingleton extends Singleton {
    public SubclassSingleton() {

    }
}


SubclassSingleton x =  new SubclassSingleton();
SubclassSingleton y = new SubclassSingleton();
System.out.println(x.getInstance() == y.getInstance()); // true

Yes, technically x and y are instances of Singleton, but getting there instance still results in a shared resource, and the constructor (from my understanding) after constructing x has essentially no effect—rather, the static method getInstance() will return the shared consstruction of the parent class. So, I'm having trouble understanding how this violates essentially having one shared instance of Singleton, despite being subclassed.

Aucun commentaire:

Enregistrer un commentaire