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

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

    Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

    The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,

    public class Singleton {
        private static Singleton instance;
    
        /**
         * A private Constructor prevents any other class from
         * instantiating.
         */
        private Singleton() {
            // nothing to do this time
        }
    
        /**
         * The Static initializer constructs the instance at class
         * loading time; this is to simulate a more involved
         * construction process (it it were really simple, you'd just
         * use an initializer)
         */
        static {
            instance = new Singleton();
        }
    
        /** Static 'instance' method */
        public static Singleton getInstance() {
            return instance;
        }
    
        // other methods protected by singleton-ness would be here...
        /** A simple demo method */
        public String demoMethod() {
            return "demo";
        }
    }
    

    Note that the method of using “lazy evaluation” in the getInstance() method (which is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy loading.” Your singleton class will probably not get loaded unless its getInstance() is called, so there is no point in trying to defer the singleton construction until it’s needed by having getInstance() test the singleton variable for null and creating the singleton there.

    Using this class is equally simple: simply get and retain the reference, and invoke methods on it:

    public class SingletonDemo {
        public static void main(String[] args) {
            Singleton tmp = Singleton.getInstance();
            tmp.demoMethod();
        }
    }
    

    Some commentators believe that a singleton should also provide a public final clone() method that just throws an exception, to avoid subclasses that “cheat” and clone() the singleton. However, it is clear that a class with only a private constructor cannot be subclassed, so this paranoia does not appear to be necessary.

提交回复
热议问题