Advantages, disadvantages and usage scenarios of the singleton pattern

【Foreword】

   Share a good article about the advantages, disadvantages and usage scenarios of the singleton pattern

 

【main body】

Advantages, disadvantages and usage scenarios of the simple interest pattern 

First, let's introduce the singleton pattern: 
    Singleton pattern (Singleton), also called singleton pattern, is a commonly used software design pattern. When applying this pattern, the class of the singleton object must ensure that only one instance exists. Many times the entire system only needs to have one global object, which helps us coordinate the behavior of the system as a whole. For example, in a server program, the configuration information of the server is stored in a file, and the configuration data is uniformly read by a singleton object, and then other objects in the service process obtain the configuration information through the singleton object. This approach simplifies configuration management in complex environments. 

The idea of ​​​​implementing the singleton pattern is: 
    a class can return a reference to the object (always the same) and a method to obtain the instance (must be a static method, usually using the name getInstance); when we call this method, if the class If the reference held by the class is not null, the reference is returned. If the reference held by the class is null, an instance of the class is created and the reference of the instance is assigned to the reference held by the class; at the same time, we also define the constructor of the class as a private method , so that the code elsewhere cannot instantiate the object of the class by calling the constructor of the class, and only obtain the only instance of the class through the static method provided by the class. 

Note: 
    The singleton pattern must be used carefully in multithreaded applications. If two threads call the creation method at the same time when the unique instance has not been created, they do not detect the existence of the unique instance at the same time, so they each create an instance at the same time, so that two instances are constructed, thus violating the single instance The principle of instance uniqueness in the instance pattern. The solution to this problem is to provide a mutex for the variable that indicates whether the class has already been instantiated (although this is less efficient). 

Advantages: 
    1. In the singleton pattern, there is only one instance of the active singleton, and all instantiations of the singleton class get the same instance. This prevents other objects from instantiating themselves, ensuring that all objects access an instance 
    2. The singleton mode has certain scalability. The class itself controls the instantiation process, and the class has corresponding scalability in changing the instantiation process. 
    3. Provides controlled access to unique instances. 
    4. Since there is only one object in the system memory, system resources can be saved, and the singleton mode can undoubtedly improve the performance of the system when objects need to be frequently created and destroyed. 
    5. Allow a variable number of instances. 
    6. Avoid multiple occupation of shared resources. 
Disadvantages: 
    1. Not suitable for changing objects. If objects of the same type always change in different use case scenarios, the singleton will cause data errors and cannot save each other's state. 
    2. Since there is no abstraction layer in the simple interest pattern, it is very difficult to extend the singleton class. 
    3. The responsibility of the singleton class is too heavy, which violates the "single responsibility principle" to a certain extent. 
    4. Abusing singletons will bring some negative problems. For example, in order to save resources, the database connection pool object is designed as a singleton class, which may lead to too many programs sharing connection pool objects and connection pool overflow; if the instantiated object If it is not used for a long time, the system will consider it as garbage and be recycled, which will lead to the loss of object state. 
Precautions for use: 
    1. Do not use the reflection mode to create a singleton, otherwise a new object will be instantiated 
    2. Pay attention to thread safety issues when using the lazy singleton mode 
    3. Both the hungry singleton mode and the lazy singleton mode construction methods It is private, so it cannot be inherited. Some singleton patterns can be inherited (such as registration patterns). 
Applicable scenarios: 
    singleton patterns only allow the creation of one object, thus saving memory and speeding up object access, so objects need to be public It is suitable for use in situations where multiple modules use the same data source to connect objects and so on. Such as: 
    1. Objects that need to be frequently instantiated and then destroyed. 
    2. Objects that take too much time or consume too many resources when creating objects, but are often used. 
    3. Stateful utility objects. 
    4. Objects that frequently access databases or files. 
The following are the classic usage scenarios of the singleton mode: 
    1. In the case of resource sharing, avoid performance or loss caused by resource operations. Apply the configuration as in the log file above. 
    2. In the case of controlling resources, it is convenient to communicate with each other between resources. Such as thread pools, etc. 
Examples of application scenarios: 
    1. External resources: each computer has several printers, but there can only be one PrinterSpooler to avoid two print jobs being output to the printer at the same time. Internal resources: Most software has one (or more) property files to store system configuration, such a system should have an object to manage these property files 
    2. Windows Task Manager (task manager) is a typical singleton pattern ( This is very familiar), think about it, isn't it, can you open two windows task managers? If you don't believe me, try it yourself~ 
    3. The Recycle Bin of windows is also a typical singleton application. During the whole system operation, the recycle bin maintains only one instance. 
    4. The counter of the website is generally implemented in a singleton mode, otherwise it is difficult to synchronize. 
    5. The log application of the application is generally implemented in the singleton mode. This is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content is not easy to append. 
    6. The reading of the configuration object of the Web application generally also applies the singleton mode, because the configuration file is a shared resource. 
    7. The design of the database connection pool generally adopts the singleton mode, because the database connection is a kind of database resource. The use of database connection pools in database software systems is mainly to save the efficiency loss caused by opening or closing database connections. This efficiency loss is still very expensive, because the use of singleton mode for maintenance can greatly reduce this loss. . 
    8. The design of multi-threaded thread pools generally adopts the singleton mode, because the thread pool needs to facilitate the control of the threads in the pool. 
    9. The file system of the operating system is also a specific example of the implementation of the large singleton pattern. An operating system can only have one file system. 
    10. HttpApplication is also a typical application of a unit case. Those who are familiar with the entire request life cycle of ASP.Net (IIS) should know that HttpApplication is also a singleton mode, and all HttpModules share an instance of HttpApplication. 
   
The principles and processes for implementing the simple interest mode: 
    1. Singleton mode: ensure that a class only has An instance, instantiate itself and provide this instance to the system 
    2. Singleton mode classification: hungry singleton mode (instantiate an object for its own reference when the class is loaded), lazy singleton mode (when calling the method of obtaining an instance such as getInstance Objects will be instantiated) (the performance of the hungry singleton mode in java is better than the lazy singleton mode, and the lazy singleton mode is generally used in c++) 
    3. Singleton mode elements: 
        a. Private constructor 
        b. Private static reference points to its own instance 
        c. Public static methods with their own instance as the return 

value (preload method) 

/**
* Hungry Chinese style (recommended)
*
*/
public class Test {
        private Test() {
        }
        public static Test instance = new Test();
        public Test getInstance() {
                return instance;
        }
}


Advantages 
    1. Thread safety 
    2. A static object has been created at the same time as the class is loaded, and the response is fast when called. The 
disadvantage  is that the
    resource efficiency is not high. Maybe getInstance() will never be executed, but other static methods or loading of the class will be executed. The class (class.forName), then the instance is still initialized 


2. Lazy: the singleton instance is constructed when it is used for the first time, lazy initialization. 

class Test {
        private Test() {
        }
        public static Test instance = null;
        public static Test getInstance() {
                if (instance == null) {
              //When multiple threads judge that the instance is null, there will be duplication in multiple threads when executing the new operation
                        instance = new Singleton2();
                }
                return instance;
        }
}


Advantages: 
    It avoids the hungry Chinese-style creation of instances when they are not used, and the resource utilization is high. If getInstance() is not executed, it will not be instanced, and other static methods of the class can be executed. 
Disadvantages: 
    The lazy style has no problem in a single thread, but when colleagues from multiple threads access, they may create multiple instances, and these multiple instances are not the same object, although the instance created later will overwrite the instance created first, but There will still be cases where different objects are obtained. The solution to this problem is to lock synchonized, the first load is not fast enough, and the unnecessary synchronization overhead of multi-threading is large. 

3. Double detection 

class Test {
        private Test() {
        }
        public static Test instance = null;

        public static Test getInstance() {
                if (instance == null) {
                        synchronized (Test.class) {
                                if (instance == null) {
                                        instance = new Test();
                                }
                        }
                }
                return instance;
        }
}


Advantages 
    High resource utilization, no instance will be executed if getInstance() is not executed, and other static methods of this class can be executed 
Disadvantages 
    The response is not fast when loaded for the first time, and occasionally fails due to some reasons of the java memory model 


4. Static inner class 

class Test {
        private Test() {
        }

        private static class SingletonHelp {
                static Test instance = new Test();
        }

        public static Test getInstance() {
                return SingletonHelp.instance;
        }
}


Advantages 
    High resource utilization, no getInstance() is executed, and other static methods of this class can be executed. 
Disadvantages 
    The response is not fast enough when loading for the first time. 

Summary: 
    Generally, hungry Chinese style is used. If you are very concerned about resources, you can use static inner classes Lazy and double detection is not recommended 

Guess you like

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