What is the implementation method of the Java singleton pattern?

There are several ways to implement the singleton pattern in Java.

  1. Eager initialization: a singleton object is created when the class is loaded, and it is returned through a static method. This approach is safe in a multi-threaded environment.
public class Singleton {
    private static final Singleton instance = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return instance;
    }
}
  1. Lazy Initialization: The singleton object is created only when the method to obtain it is called. This method requires thread synchronization in a multi-threaded environment.
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. Double-Checked Locking: An improvement on the lazy initialization method, adding an extra null check when creating an instance to reduce unnecessary synchronization overhead.
public class Singleton {
    private volatile static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. Static Inner Class: Utilize the characteristics of a static inner class to achieve lazy loading and ensure thread safety.
public class Singleton {
    private Singleton() {}

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

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}
  1. Enumeration (Enum): Using the properties of enumeration to implement the singleton pattern. Enumerations are thread-safe and will only be instantiated once.
public enum Singleton {
    INSTANCE;

    // 需要添加的单例对象的其他方法
}
bannerAds