其他分享
首页 > 其他分享> > 单例模式(DCL, 静态内部类, 枚举)

单例模式(DCL, 静态内部类, 枚举)

作者:互联网

双重检查锁(double checked locking)

只在第一次调用getInstance时, 进行同步加锁

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

静态内部类实现

class Singleton2{
    private Singleton2(){}

    private static class innerClass{
        private static Singleton2 instance =new Singleton2();
    }
    public static Singleton2 getInstance(){
        return innerClass.sa;
    }
}

枚举

enum Singleton3{
	instance;
}

标签:DCL,private,instance,枚举,DclSingleton,单例,Singleton2,static,class
来源: https://blog.csdn.net/qq_43868654/article/details/120432525