Singleton java idioma design template

I am very confused. I found many implementations of the Singleton design pattern in java. One of the found implementations is as follows:

public class MySingleton {

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

    private MySingleton () {}

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

as described here: qaru.site/questions/65513 / ... . Now, if this implementation should work, why not the following?

public class MySingleton {

    private static final MySingleton INSTANCE = new MySingleton();

    private MySingleton () {}

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

, java , , , . : qaru.site/questions/23102/..., , , , singleton , INSTANCE (getInstance). , : , singleton?

+4
2

.
.
, singleton getInstance() .
.
, singleton , MySingleton .

, getInstance() singleton .
, getInstance().

, ( ), .

+5

Java enum. enum, (aka "enumerate" ) , - . , , ; "singleton". ( " " , .)

, :

public enum MySingleton {
    INSTANCE();

    /* delcare instance fields here. */

    /** constructor; give it params if you need to. */
    public MySingleton() {
        // initialize whatever you need here.
    }

    /* methods you'll use go here. */
}

, MySingleton.INSTANCE.

+1

Source: https://habr.com/ru/post/1684498/


All Articles