单例

什么是单例?

单例类在整个程序中只能有一个实例,这个类负责创建自己的对象,并确保只有一个对象被创建

代码实现要点

  • 私有构造方法

  • 只有该类属性

  • 对外提供获取实例的静态方法

//饿汉
public class Singleton {
    //提供私有构造方法
    private Singleton() {}
​
    //一出来,就加载创建
    private static Singleton instance = new Singleton();
    
    public static Singleton getInstance(){
        return instance;
    }
}
//懒汉
public class Singleton {
    //提供私有构造方法
    private Singleton() {}
    //第一次使用,才加载创建
    private static Singleton instance = null;
    
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

懒汉模式效率低下

双检锁/双重校验锁(DCL,即 double-checked locking)

安全且在多线程情况下能保持高性能

//双检锁
public class Singleton {
​
    private Singleton() {}
    
    private static Singleton instance = null;
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            } 
        }
        return instance;
    }
}

 

原文地址:https://www.cnblogs.com/hellojava404/p/13150544.html