单例模式的三种最佳方式

  • 1,提前初始化

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

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

  • 2.双重检查锁定 + volatile。

    public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {
    }

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

  • 3.延迟初始化占位类模式。

    public class Singleton {
    private static class InstanceHolder {
    public static Singleton instance = new Singleton();
    }

    private Singleton() {
    }

    public static Singleton getInstance() {
    return InstanceHolder.instance;
    }
    }

你可能感兴趣的:(单例模式的三种最佳方式)