vendredi 25 août 2017

Singleton design pattern java idioma

I'm quite confused. I found many implementations of the Singleton Design Pattern in java. One of the implementations I found is the following:

public class MySingleton {

    private static class Loader {
        static MySingleton INSTANCE = new MySingleton();
    }

    private MySingleton () {}

    public static MySingleton getInstance() {
        return Loader.INSTANCE;
    }
}

as explained here: http://ift.tt/1jBnDYz. Now, if this implementation should work, why doesn't the following?

public class MySingleton {

    private static final MySingleton INSTANCE = new MySingleton();

    private MySingleton () {}

    public static MySingleton getInstance() {
        return INSTANCE;
    }
}

I searched around how java handles initializations, but couldn't find anything showing the latter code will not work. Instead, I found the following: stackoverflow.com, which points out that every static initialization happen before a static method of the class is invoked, so the static field holding the singleton instance should be initialized when the only method accessing INSTANCE (getInstance) is invoked. So yes, i'm really confused: if this code works, why not using this simpler version of the singleton design pattern?

Aucun commentaire:

Enregistrer un commentaire