设计模式之单例模式

设计模式之单例模式

这是设计模式系列的第一篇——单例模式,记录自己的学习过程,也希望对你有帮助。如有错误,请批评指出,谢谢!!!

单例对象通俗的讲就是让一个类只构建一个对象。

  • 非线程安全单例模式
public class singleton {                            //单例模式类
    private singleton () {}                         //私有构造函数
    private static singleton instance = null;       //单例对象

    public static singleton getInstance () {        //静态get单例的方法
        if (instance == null) {
                instance = new singleton;           //如果单例对象为空创建一个单例对象
        }
        return instance;
    }
}
  • 线程安全单例模式低级版
public class singleton {                            //单例模式类
    private singleton () {}                         //私有构造函数
    private static singleton instance = null;       //单例对象

    public static singleton getInstance () {        //静态get单例的方法
        if (instance == null) {                     
            synchronized (this) {                   //增加同步锁,保证线程安全
             if (instance == null) {               //这里做两次判空是因为如果两个线程同时走到了上一个if (instance == null),其中一个线程先加锁执行,另一个线程已经做完第一个判空,如不做第二次判空,还是会构建对象
                    instance = new singleton;      //如果单例对象为空创建一个单例对象
                }   
            }
        }
        return instance;
    }
}
  • 线程安全单例模式高级版
public class singleton {                            //单例模式类
    private singleton () {}                         //私有构造函数
    private volatile static singleton instance = null;       //volatile关键字防止指令重排,保证线程访问的变量值是主内存中的最新值

    public static singleton getInstance () {        //静态get单例的方法
        if (instance == null) {
            synchronized (this) {
             if (instance == null) {               
                    instance = new singleton;      //如是低级版,可能由于JVM的指令重排导致不是完全线程安全的
                }   
            }
        }
        return instance;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值