Singleton pattern learning for Java design patterns

  • 2020-04-01 02:45:07
  • OfStack

1 overview

The singleton pattern has several benefits:

(1) some classes are created quite frequently, which is a lot of overhead for some large objects.

(2) the new operator is omitted, which reduces the use frequency of system memory and reduces GC pressure.

(3) some classes, such as the core trading engine of an exchange, control the trading process, and if this class can create more than one, the system is completely out of order.

2,

There are two common ways to write the singleton pattern.

2.1 the hungry

If your application is always creating and using the singleton pattern, or if there is not a lot of pressure to create and run, you can use a private static variable to create the object ahead of time.


package org.scott.singleton;

public class Singleton1 {
    private static Singleton1 uniqueInstance = new Singleton1();

    private Singleton1(){

    }

    public static Singleton1 getInstance(){
        return uniqueInstance;
    }
}

By doing so, when the JVM loads the class, the objects are created in the order in which they were initialized. At the same time, the JVM guarantees that any thread must create the instance before accessing the singleton, and only once.

Of course, you can use a static inner class to do the same thing.


package org.scott.singleton;

public class Singleton2 {  

    private Singleton2() {  
    }  

      
    private static class SingletonFactory {  
        private static Singleton2 instance = new Singleton2();  
    }  

    public static Singleton2 getInstance() {  
        return SingletonFactory.instance;  
    }  

      
    public Object readResolve() {  
        return getInstance();  
    }  
}

2.2 double lock mode
  Double locks, as the name implies, are two locks, the first to check if the instance object to be created has already been created, and the second to synchronize if it has not.


package org.scott.singleton;

public class Singleton3 {
    private volatile static Singleton3 uniqueInstance;

    private Singleton3(){

    }

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

This approach can significantly reduce creation time if performance requirements are high, and is currently a more common way to create singletons.


Related articles: