jeudi 3 septembre 2015

Singleton pattern: static or static final?

It is better to declare the instance of a Singleton as static or as 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;
    }

}

Aucun commentaire:

Enregistrer un commentaire