首页 > 其他 > 详细

单例模式

时间:2020-04-04 22:36:18      阅读:57      评论:0      收藏:0      [点我收藏+]
#懒汉式,线程安全
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)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!