Singleton pattern: static or static ending?

Better to declare an instance of Singleton as staticor how static final?

See the following example:

static version

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }

}

static final version

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

}
+4
source share
3 answers

In your specific cases there is no difference. And your second is already effective final .

But

Leaving aside the fact that the implementation below is not thread safe, simply showing the difference with respect to the final.

In case of lazy initialization of your instance, you can feel the difference. Look at lazy initialization.

public class Singleton {

    private static Singleton INSTANCE; /error

    private Singleton() {
    }

    public static Singleton getInstance() {
      if (INSTANCE ==null) {
         INSTANCE = new Singleton(); //error
      }
        return INSTANCE;
    }

}
+2
source

( ), final, () - :

class Sample {
   static Object o = new Object(); // o is not final. Hence can change.
    static{
     o = new Object();
     o = new Object();
    }
}

Singleton Enum .

0

static .

public class Singleton {

    private static Singleton instance = null;

    private Singleton() {
    }

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

}

, , . .

-2

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


All Articles