[Reading Notes] "Big Talk Design Pattern" Singleton Mode

1. What is the singleton pattern

 The singleton pattern is a commonly used software design pattern, and its definition is that only one instance of the singleton object class can exist.

 Many times the entire system only needs to have one global object, which helps us coordinate the overall behavior of the system. 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.

2. Features of singleton mode

 Singleton mode: Ensure that a class has only one instance, and provide a global access point to access it.

3. Application scenarios of singleton mode

 To give a small example, on our windows desktop, we opened a recycle bin. When we try to open a new recycle bin again, the Windows system will not pop up a new recycle bin window for you. , That is to say, during the operation of the entire system, the system only maintains one instance of the recycle bin. This is a typical singleton pattern application.

 Continuing to talk about the recycle bin, we do not need to open two recycle bin windows at the same time in actual use. If I need to consume a lot of resources every time I create a recycle bin, and the resources between each recycle bin are shared, then there is no need to create multiple instances of the instance repeatedly, so that Will cause unnecessary burden to the system and cause waste of resources.

  To give another example, the counter of a website is generally implemented in a singleton mode. If you have multiple counters, the value of the counter will be refreshed for each user's visit. In this way, the value of your actual count is difficult to synchronize. But if the singleton mode is adopted, there will be no such problems, and thread safety problems can be avoided. The same multi-threaded thread pool design generally adopts the singleton mode, because the thread pool needs to facilitate the control of the threads in the pool.

 Similarly, for some application log applications, or reading configuration files in web development, it is suitable to use the singleton mode, such as HttpApplication is a typical singleton application.

 From the above examples, we can summarize the scenarios and advantages and disadvantages that are suitable for using singleton mode.

Applicable scenarios :

  • An environment that needs to generate a unique sequence
  • Objects that need to be instantiated frequently and then destroyed
  • Objects that consume too much time or resources when creating objects, but are frequently used
  • An environment that facilitates communication between resources

4. UML graphics

Insert picture description here

5. Singleton mode implementation

 The Singleton class defines a GetInstance operation that allows clients to access its only instance. GetInstance is a static method, mainly responsible for creating its own unique instance.

5.1 Lazy man

public class Singleton {
    
    
    private static Singleton instance;

    /**
     * 构造方法让其为private,这就堵死了外界利用new创建此类实例的可能
     */
    private Singleton() {
    
    }

    /**
     * 此方法是获得本类实例的唯一全局访问点
     * @return 返回本类的唯一实例
     */
    public static Singleton getInstance() {
    
    
        //若实例不存在,则new一个新实例,否则返回已有的实例
        if (instance == null)
            instance = new Singleton();

        return instance;
    }
}

 Client code:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();

        if (s1 == s2) {
    
    
            System.out.println("两个对象是相同的实例");
        }

        System.out.println(s1);
        System.out.println(s2);
    }
}

 The running result is as follows:
Insert picture description here

5.2 Hungry Chinese

/**
 * final阻止发生派生,而派生可能会增加实例
 */
public final class HungrySingleton {
    
    
    private static HungrySingleton instance = new HungrySingleton();
    
    private HungrySingleton() {
    
    }
    
    public static HungrySingleton getInstance() {
    
    
        return instance;
    }
}

 The client code and running effect are basically the same as in the 5.1 example, so I won't list them here.

Note :

 The difference between lazy man and hungry man:

  • 5.1 The example is lazy . This implementation will only instantiate itself when it is referenced for the first time, so it is called lazy singleton.
  • 5.2 The example is the hungry man type , this implementation is to instantiate itself when the class is loaded, so it is called the hungry man singleton class.

 Comparison of lazy man and hungry man:

  • Lazy , facing the security problem of multi-threaded access, need to do double locking (introduced in the next example).
  • Hungry Chinese style , that is, static initialization, it is an object that is instantiated as soon as the class is loaded, so system resources must be occupied in advance.

5.3 Double lock

public class DoubleLockSingleton {
    
    
    private static DoubleLockSingleton instance;
    private static final Object syncRoot = new Object();

    private DoubleLockSingleton() {
    
    }

    public static DoubleLockSingleton getInstance() {
    
    
        //先判断实例是否存在,不存在再加锁处理
        if (instance == null) {
    
    
            synchronized (syncRoot) {
    
    
                if (instance == null) {
    
    
                    instance = new DoubleLockSingleton();
                }
            }
        }

        return instance;
    }
}

 The client code and running effect are basically the same as in the 5.1 example, so I won't list them here.

 Here is an explanation of why it is judged whether the instance variable is null twice in double locking. When instance is null and two threads call the getInstance() method at the same time, they will all pass the first instance==null judgment. Then due to synchronizedthe mechanism, only one of these two threads enters, and the other is waiting in a queue. One of them must enter and come out before the other can enter. At this time, if there is no judgment of the second instance==null, the first thread creates an instance, and the second thread can continue to create new instances, which does not achieve the purpose of singleton.

6. The advantages and disadvantages of the singleton pattern

Advantages :

  • There is only one object in memory, saving memory space
  • Avoid frequent creation and destruction of objects, which can improve performance
  • Avoid multiple occupation of shared resources and simplify access
  • Provide a global access point for the entire system

Disadvantages :

  • Not suitable for objects that change frequently
  • Abuse of singleton 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 is not used for a long time, the system will consider the object to be garbage and be recycled, which may cause the loss of the object state

Guess you like

Origin blog.csdn.net/Handsome_Le_le/article/details/109015107