Java单例模式实现的两种方式和应用场景

单例模式的定义

个人理解,单例是指单个实例,在整个应用程序当中有且仅有一个实例存在,该实例是通过代码指定好的(自行创建的)。

为什么要使用

  1. 解决在高并发过程中,多个实例出现逻辑错误的情况。
  2. 在特定的业务场景下避免对象重复创建,节约内存。

实现的两种方式

饿汉式

顾名思义,不管有没有使用到该对象,只要程序启动成功,该单实例对象就存在。

代码如下:

/**
 * 饿汉式
 */
public class SingletonHungry {


    private static SingletonHungry instance = new SingletonHungry();

    public static SingletonHungry instance(){
        return instance;
    }

    public static void main(String[] args) {
        SingletonHungry instance1 = SingletonHungry.instance();
        SingletonHungry instance2 = SingletonHungry.instance();
        System.out.println(instance1);
        System.out.println(instance2);
    }
}

上述情况,满足在单线程和多线程中使用。

懒汉式

顾名思义,只有在程序当中使用到该对象的时候,该单实例对象才会被实例化。

代码如下:

/**
 * 懒汉式-单线程
 */
public class SingletonLazy {

    public static SingletonLazy instance = null ;

    public static SingletonLazy instance() {
        if(instance == null) {
            instance = new SingletonLazy() ;
        }

        return instance ;
    }
}

上述编写的代码中,乍一看,没问题,满足了单实例对象。可是细细一琢磨,咋感觉这不对,如果多线程情况下,就很难保证单实例对象了。下面提供一种多线程情况下实现单例的方式:

/**
 * 懒汉式-多线程
 */
public class SingletonLazy {

    public static SingletonLazy instance = null ;

    public static SingletonLazy instance() {

        if(instance == null ) {
            synchronized (SingletonLazy.class) {
                if(instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance ;
    }
}

上述的代码中满足了多线程的使用场景,就是使用了上锁+双重检查来进行实现。

欢迎交流!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆小叁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值