1.1.C-Singleton singleton pattern

Definition: It is guaranteed that a class has one and only one instance, and that it is instantiated by itself (without manual new) and provided to the entire system.
    The singleton mode can ensure that only one instance of the class exists in the system, which facilitates the control of the number of instances and the saving of system resources. If you want to have only one instance of a class in the system, the singleton pattern is the best solution. The so-called one mountain cannot accommodate two tigers, and one husband cannot have two wives, this is the truth.
Singleton pattern elements:
    1. Private Constructor
    2. Private static references point to their own instances
    3. Public static methods with their own instance as return value
scenes to be used:
    1. An environment that requires the generation of a unique serial number
    2. A shared access point or shared data is required in the entire project, such as a counter on a Web page, without logging each refresh to the database, use the singleton pattern to maintain the value of the counter, and ensure that it is thread-safe
    3. Creating an object consumes too many resources, such as accessing resources such as IO and database
    4. The environment that needs to define a large number of static constants and static methods (such as tool classes) can use the singleton mode (of course, it can also be directly declared as static)
    5. Use with configuration information, for example, put the configuration information into a properties file, and use a singleton to obtain the configuration content in the file

 

The singleton pattern is also known as the monadic pattern or the singleton pattern. There are two types of singleton modes: lazy and hungry.
lazy
/**
 * Singleton mode - lazy man
 *
 * @auth zhangjingxuan
 * @since April 11, 2018 at 9:47:50 AM
 */
public class Singleton2 {
 
    //1. Create the only instance of the class, use private static modification
    private static Singleton2 instance;
   
    //2. The construction method is privatized, and objects are not allowed to be created directly from the outside
    private Singleton2() {
        System.out.println("Singleton2 initialization completed");
    }
   
    //3. Provide a method for obtaining an instance, decorated with public static
    public static Singleton2 getInstance(){
        if(instance==null){
            instance=new Singleton2();
        }
        return instance;
    }
   
    //4. Other methods should be decorated with static as much as possible
    public static void doSomething() {
        System.out.println("Singleton2 doSomething");
    }
}
 
 
Hungry Chinese
/**
 * Singleton mode - hungry Chinese
 *
 * @auth zhangjingxuan
 * @since April 11, 2018 at 9:45:30 AM
 */
public class Singleton1 {
 
    //1. Create the only instance of the class, use private static modification
    private static Singleton1 instance = new Singleton1();
   
    //2. The construction method is privatized, and objects are not allowed to be created directly from the outside
    private Singleton1() {
        System.out.println("Singleton1 initialization completed");
    }
   
    //3. Provide a method for obtaining an instance, decorated with public static
    public static Singleton1 getInstance(){
        return instance;
    }
   
    //4. Other methods should be decorated with static as much as possible
    public static void doSomething() {
        System.out.println("Singleton1 doSomething");
    }
}
 
 
test
public class Test {
 
    public static void main(String[] args) {
        Singleton1.doSomething();
       
        Singleton2.doSomething();
    }
}
 
 
result
Singleton1 is initialized
Singleton1 doSomething
Singleton2 doSomething
 
 
Lazy vs Hungry :
    1. The main difference in coding is the first step of the above code, whether it needs to be instantiated before getInstance()
    2. The feature of lazy style is that it is faster to load classes, but slower to obtain instances at runtime, and the thread is not safe
    3. Hungry style is characterized by slow loading of classes (requires instantiation), but faster instance acquisition (getInstance()) at runtime, and thread-safety
    4. When doSomething is called directly without obtaining an instance, the operation will not be instantiated
    5. When the hungry Chinese style directly calls doSomething without obtaining an instance, the instantiation operation is still performed.
 
To sum up, the lazy mode is thread-safe, but it will waste system resources in some scenarios. Hungry mode is thread-unsafe, but saves system resources compared to lazy mode. So, if there is a way of writing that includes the characteristics of singleton, thread safety and saving system resources, it would be great! There is a saying in the programming world that "if you can think of it, we can do it for you", so this luxurious writing method also appeared.
 
Thread-safe & resource-saving singleton mode (lazy + thread lock)
/**
 * Singleton mode - lazy man
 *
 * @auth zhangjingxuan
 * @since April 11, 2018 at 9:47:50 AM
 */
public class Singleton3 {
 
    //1. Prevent the use of reflection to call the singleton, thereby destroying the flag of the singleton mode (which will be used in the constructor)
    private static boolean initialized = false;
 
    //2. Static inner class (parasite) to solve multi-thread safety issues
    private static class LazyHolder {
        private static final Singleton3 instance = new Singleton3();
    }
   
    //3. Constructor (used with initialized)
    private Singleton3() {
        //Resolve reflection destruction to singleton
        synchronized (Singleton3.class) {
            if (!initialized) {
                initialized = true;
                System.out.println("Singleton3 initialization completed");
            } else {
                throw new RuntimeException("Initialization prohibited...");
            }
        }
    }
 
    //4. Provide a method for obtaining an instance, decorated with public static
    public static Singleton3 getInstance() {
        return LazyHolder.instance;
    }
   
    public static void doSomething() {
        System.out.println("Singleton3 doSomething");
    }
}
 
 Thanks to the following bloggers, the abstract literature is from the following:

 

Guess you like

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