Should a Java singleton use static variables?

This question already has an answer here:

  • Difference between static class and singleton pattern? 36 answers

  • You should use member variables. A singleton is an object (ie an instance of a class) and so should be modelled as such; even if you only ever intend to create one of them.

    Statics should be used for class level variables.


    There needs to be a static reference to the singleton instance, but the instance itself should use instance variables, just like a regular class.

    The reason is that the singleton instance is after all an object, so the usual good design principles still apply to its class.

    Further, today it's a singleton, but tomorrow it may be a ThreadLocal, or not have any kind of instance creation restrictions. The change between these architectural choices is very low if the class is designed in the usual way. If you use static fields, such changes would require more maintenance work to make the fields non-static.


    You can avoid using static variables and use Enum instead:

    public enum MySingleton {
        INSTANCE;
    }
    

    You can access this singleton as MySingleton.INSTANCE .

    Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.

    链接地址: http://www.djcxy.com/p/78814.html

    上一篇: PHP:单例与静态类

    下一篇: Java单例应该使用静态变量吗?