Java Design Pattern Road "Three" Singleton Pattern

Singleton pattern (Singleton)

 

Singleton is a common design pattern. In Java applications, a singleton object ensures that only one instance of the object exists in a JVM. Such a pattern has several benefits:

1. Some classes are created more frequently. For some large objects, this is a large system overhead.

2. The new operator is omitted, which reduces the frequency of system memory usage and reduces GC pressure.

3. Some classes, such as the core trading engine of the exchange, control the transaction process. If more than one class can be created, the system will be completely messed up.

 

//method one
public class Singleton {
    /* Private constructor to prevent instantiation */
    private Singleton() {
    }
    /* Use an inner class here to maintain the singleton */
    private static class SingletonFactory {
        private static Singleton instance = new Singleton();
    }
    /* get instance */
    public static Singleton getInstance() {
        return SingletonFactory.instance;
    }
    /* If the object is used for serialization, the object can be guaranteed to be consistent before and after serialization */
    public Object readResolve() {
        return getInstance();
    }
}
//Method Two
public class Singleton {
    //Set its own instance object as a property, and add Static and final modifiers
    private static final Singleton instance = new Singleton();
    // make the constructor private
    private Singleton() {
    }
    //Provide an instance of this class to the outside world through a static method
    public static Singleton getInstance() {
        return instance;
    }
}
//method three
class Singleton {
    private static Singleton instance = null;
    public static Singleton getInstance() {
        if (instance == null) {
            Synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance2;
    }
}

 

// method four
class Singleton {
    private static Singleton instance = null;
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Note: The four methods achieve the same function, the first and second methods are recommended, and the third and fourth methods are inefficient (three is higher than four).

Guess you like

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