How to make sure that there is just one instance of class in JVM?

后端 未结 9 1529
离开以前
离开以前 2021-02-01 05:48

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a s

相关标签:
9条回答
  • 2021-02-01 06:28

    There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.

    Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter. The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).

    0 讨论(0)
  • 2021-02-01 06:32

    That's the well known Singleton pattern: you can implement this as follows:

    public class SingletonClass {
    
        //this field contains the single instance every initialized.
        private static final instance = new SingletonClass();
    
        //constructor *must* be private, otherwise other classes can make an instance as well
        private SingletonClass () {
            //initialize
        }
    
        //this is the method to obtain the single instance
        public static SingletonClass getInstance () {
            return instance;
        }
    
    }
    

    You then call for the instance (like you would constructing a non-singleton) with:

    SingletonClass.getInstance();
    

    But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...

    0 讨论(0)
  • 2021-02-01 06:36

    Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.

    See this StackOverflow question for more details: Implementing Singleton with an Enum (in Java)

    Discussion: http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html

    0 讨论(0)
提交回复
热议问题