继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

单例模式总结

慕标5832272
关注TA
已关注
手记 1071
粉丝 228
获赞 996

单例模式

1.懒汉模式

public class Singleton{    private static Singleton instance = new Singleton();    private Singleton(){
    }    public static Singleton getInstance(){
        retuurn instanace;
    }
}

重点:当程序没有调用获取实例方法时,虚拟机已经加载了此类并调用了构造方法,没有延时加载的功能

2.饿汉模式

public class Singleton{    private static Singleton instance;    private Singleton(){
    }    public static Singleton getInstance(){        if(null == instance){
            instance = new Singleton();
        }        return instance;
    }
}

重点:有延时加载功能,但线程不安全,当在多线程场景中,可能出现多个实例

3.DCL

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

重点: 实例化时虚拟机存在指令重排序优化,依然会导致线程不安全,可将instance对象用volatile修饰

4.静态内部类

public class Singleton{    private Singleton(){}    private static class SingletonHolder{        private static final Singleton instance = new Singleton();
    }    public static Singleton getInstance(){        return SingletonHolder.instance;
    }
}

重点:延时加载、线程安全,推荐使用

5.枚举

public enum Singleton{
    INSTANCE;
}



作者:进击的欧阳
链接:https://www.jianshu.com/p/e94d3828da84


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP