Best implementation of the singleton pattern

    The first one: Hungry-style simple interest mode, a class instance will be created when the singleton class is loaded
    public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
        public static Singleton getInstance() {
            return instance;
        }
    }
    The second: lazy singleton mode: (delayed loading idea) The core of this idea is to load the resource or obtain the data until the resource or data needs to be used, which can save the memory space before use as much as possible , the generally recommended singleton mode is the lazy mode.
    public class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
        public static Singleton getInstance() {
            // If instance is not initialized, initialize the class instance
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    The third: thread-safe lazy singleton pattern:
    public class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
        public static synchronized Singleton getInstance() {
            // If instance is not initialized, initialize the class instance
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    The fourth: thread-safe lazy simple profit mode: (double check locking mechanism): every time the program calls the getInstance() method, it does not synchronize first, but checks whether the class instance exists after entering the method. If it does not exist, enter the next synchronization code block; after entering the synchronization code block, it will check whether the class instance exists again, and if not, create a new instance, so that only one synchronization needs to be performed when the class instance is initialized It is enough to judge, instead of synchronous judgment every time the getInstance() method is called, which greatly saves time.
    public class Singleton {
    /**
     * No class instance is created when loading, but a class variable needs to be used to save the subsequently created class instance
     * Add the volatile keyword so that it will not be cached by the local thread to ensure that the thread can handle it correctly
     * Add the static keyword to make the variable available in the getInstance() static method
     */
    private volatile static Singleton instance = null;
    private Singleton() {}
        public static Singleton getInstance() {
            // First check: if instance is not initialized, enter synchronized block
            if (instance == null) {
                // Synchronized code block to ensure thread safety
                synchronized (Singleton.class) {
                    // Second check: if instance is not initialized, initialize the class instance
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    Fifth: Since there is a single-case mode, will there be a double-case mode, a three-case mode, etc.
    public class Singleton {
        // The maximum number of class instances that can be created, here is an example of "dual instance mode"
        private static final int MAX = 2;
        // The class instance caches the KEY value
        private static final String KEY = "CACHE";
        // current instance number in use
        private static int index = 1;
        // class instance cache container
        private static Map<String, Singleton> map = new HashMap<>();
        /**
        * Private constructors, so that outsiders cannot construct class instances other than instance through the constructors
        * In order to achieve the purpose of controlling the number of class instances in singleton mode
        */
        private Singleton() {}
        /**
        * Global access method for class instance
        * Add the static keyword so that the outside can directly call this method through the class name to obtain the class instance
        * @return singleton class instance
        */
        public static Singleton getInstance() {
            // Try to get the index-th class instance from the cache container
            String key = KEY + index;
            Singleton instance = map.get(key);
            // If the class instance cannot be obtained, initialize the instance and cache it in the corresponding index of the container
            if (instance == null) {
                instance = new Singleton();
                map.put(key, instance);
            }
            // Here we take the most basic sequential call as an example, and other complex scheduling methods are not discussed. The specific calling methods are as follows
            // index++, to get the next class instance in the next call, when the upper limit of the number of class instances is reached, re-acquire the first class instance
            if ((++index) > MAX) {
                index = 1;
            }
            return instance;
        }
    }
    The sixth: the best implementation of the singleton pattern:
    public class Singleton {
        /**
         * Class-level inner class for caching class instances
         * The class will be loaded when called, thus implementing lazy loading
         * At the same time, since the instance is statically initialized, the JVM can ensure its thread safety
         */
        private static class Instance {
            private static Singleton instance = new Singleton();
        }
        /**
         * Private constructors, so that outsiders cannot construct class instances other than instance through the constructors
         * In order to achieve the purpose of controlling the number of class instances in singleton mode
         */
        private Singleton() {}
        /**
         * Global access method for class instance
         * Add the static keyword so that the outside can directly call this method through the class name to obtain the class instance
         * @return singleton class instance
         */
        public static Singleton getInstance() {
            return Instance.instance;
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325755378&siteId=291194637