JAVA design pattern 1: Singleton mode, ensuring that each class can only have one instance

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the singleton pattern in the Java design pattern, and gives sample code, the singleton pattern, ensures that each class can only have one instance, and provides a global access point to obtain the instance.

insert image description here


1. What is the singleton pattern

Singleton pattern in Java is a design pattern that ensures that there can only be one instance of a certain class and provides a global access point to obtain that instance .

There are many ways to implement the singleton mode, among which there are two most commonly used ways: the lazy man's style and the hungry man's style .

1.1 Lazy singleton pattern

The lazy style only creates the object when the method for obtaining the instance is called for the first time .

The following is a common lazy-style singleton mode implementation, please study carefully.

   public class Singleton {
    
    
       private static Singleton instance;
   
       private Singleton() {
    
    
           // 私有构造方法
       }
   
       public static synchronized Singleton getInstance() {
    
    
           if (instance == null) {
    
    
               instance = new Singleton();
           }
           return instance;
       }
   }

Tip: The above implementation can work normally in a multi-threaded environment, but due to the synchronization lock added to the method of obtaining the instance, the performance will decrease.

1.2 Hungry Chinese style singleton mode

Hungry style creates objects when the class is loaded, so it is guaranteed that there is only one instance at any time .

The following is a common implementation of the Hungry Chinese singleton pattern, please study carefully.

   public class Singleton {
    
    
       private static final Singleton instance = new Singleton();
   
       private Singleton() {
    
    
           // 私有构造方法
       }
   
       public static Singleton getInstance() {
    
    
           return instance;
       }
   }

Tip: Hungry Chinese style can ensure that it can work normally in a multi-threaded environment, but it may cause waste of resources, because the instance is created when the class is loaded.

1.3 Summary of Lazy/Hungry Single Case

Regardless of whether you use the lazy style or the hungry style, the singleton mode needs to pay attention to issues such as thread safety, serialization, and reflection . If you need better thread safety and higher performance, you can consider using double-checked locking or static inner classes to implement the singleton pattern.

insert image description here


2. What are the singleton patterns?

In the first chapter, the singleton mode is briefly introduced, followed by a detailed introduction and detailed code.

In Java, there are several ways to implement the singleton pattern.

2.1 Lazy Initialization singleton pattern

public class LazySingleton {
    
    
    private static LazySingleton instance;

    private LazySingleton() {
    
    
        // 私有构造方法
    }

    public static synchronized LazySingleton getInstance() {
    
    
        if (instance == null) {
    
    
            instance = new LazySingleton();
        }
        return instance;
    }
}

2.2 Eager Initialization singleton mode

public class EagerSingleton {
    
    
    private static final EagerSingleton instance = new EagerSingleton();

    private EagerSingleton() {
    
    
        // 私有构造方法
    }

    public static EagerSingleton getInstance() {
    
    
        return instance;
    }
}

2.3 Double-Checked Locking (Double-Checked Locking) singleton mode

public class DoubleCheckedSingleton {
    
    
    private volatile static DoubleCheckedSingleton instance;

    private DoubleCheckedSingleton() {
    
    
        // 私有构造方法
    }

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

2.4 Static Inner Class singleton mode

public class StaticInnerSingleton {
    
    
    private StaticInnerSingleton() {
    
    
        // 私有构造方法
    }

    private static class SingletonHolder {
    
    
        private static final StaticInnerSingleton instance = new StaticInnerSingleton();
    }

    public static StaticInnerSingleton getInstance() {
    
    
        return SingletonHolder.instance;
    }
}

The above are the implementation methods of several commonly used singleton patterns. When implementing singleton patterns, issues such as thread safety, serialization, and reflection need to be considered.

insert image description here


3. Application scenarios of singleton mode

The singleton pattern is in the following 5 55 cases are often used, please study carefully.

  1. Resource sharing : When multiple objects need to share the same resource, using the singleton mode can ensure that only one instance is created, thereby avoiding repeated creation and waste of resources.
  2. Configuration information : Singleton mode can be used to manage global configuration information to ensure the consistency and uniqueness of configuration information.
  3. Logger : In the scenario of a logger, the singleton mode can ensure that there is only one instance of the logger, which is convenient for unified management and logging.
  4. Database connection pool : In the implementation of the database connection pool, using the singleton mode can ensure that only one connection pool is created, thereby avoiding the abuse and waste of connection resources.
  5. Thread pool : In a multi-threaded scenario, using the singleton mode can ensure that there is only one thread pool instance, which is convenient for managing and controlling thread resources.

In general, the singleton mode is suitable for scenarios that require global access in the system and only one instance, and can provide a simple, convenient and safe solution. However, excessive use of the singleton pattern may lead to increased code coupling and should be used with caution.

insert image description here


4. Singleton mode interview questions

  1. Please explain what is the singleton pattern and what does it do?
  2. Please list several common implementations of singleton mode, and explain their advantages and disadvantages respectively.
  3. How to ensure that the singleton pattern works correctly in a multi-threaded environment?
  4. Can the singleton pattern be inherited and cloned?
  5. How to prevent breaking the implementation of the singleton pattern through reflection?
  6. Does the singleton pattern have thread safety issues? If yes, how to solve it?
  7. What is the difference between a hungry man's style and a lazy man's singleton pattern? Which way to use in what situation?
  8. What scenarios is the singleton pattern suitable for? Please give an example.
  9. What are the advantages and disadvantages of the singleton pattern?
  10. Besides the singleton pattern, what are the related design patterns?

V. Summary

This article explains the singleton pattern in the Java design pattern and gives sample code. In the next blog, I will explain the Java factory method pattern.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/131986264