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

后端 未结 9 1657
离开以前
离开以前 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: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...

提交回复
热议问题