设计模式--单例模式最佳实践

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16247851/article/details/88950315

1.double-check懒汉模式

public class Singleton {
    private Singleton() {   }
    private static Object INSTANCE = null;
    public static Object getInstance() {
        if(INSTANCE == null){
            synchronized(Singleton3.class){
                if(INSTANCE == null){
                    INSTANCE = new Object();
                }
            }
        }
        return INSTANCE;
    }
}

 2.volatile的解决方案

public class Singleton {
    private Singleton() {}
    private static volatile Object INSTANCE = null;
    public static Object getInstance() {
        if(INSTANCE == null){
            synchronized(Singleton.class){
                if(INSTANCE == null){
                    INSTANCE = new Object();
                }
            }
        }
        return INSTANCE;
    }
}

3.枚举实现

public enum Singleton {
    INSTANCE;
    public String getInfo(String s){
      
        return s;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16247851/article/details/88950315