单例模式

时间:2020-04-04 22:36:18   收藏:0   阅读:57
#懒汉式,线程安全
public class Singleton{
    private static Singleton instance;
    private Singleton(){}
    public static synchronized Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
    }
    return instance;  
    }
}

#优点:第一次调用才初始化,避免内存浪费。
#缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。
#饿汉式
public class Singleton{
    private static Singleton instance = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}
#双检锁/双重校验锁
public class Singleton{
    private volatile static Singleton singleton;
    private Singleton(){}
    public static Singleton getSingleton(){
    if (singleton==null){
        synchronized (Singleton.class){
        if (single == null){
        singleton = new Singleton();
        }
        }
    }
    return singleton;
    }  
}

 

原文:https://www.cnblogs.com/liushoudong/p/12634416.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!