彻底搞懂单例模式

什么是单例模式(What)

在进程中,一个类只允许创建一个对象

为什么要使用单例模式(Why)

  1. 解决资源冲突
  2. 数据只需要存在一份

单例模式的实现方式(How)

1.饿汉式

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

优点:线程安全,获取实例的速度快

缺点:类加载时实例化对象,可能不被使用,造成内存的浪费。

2.懒汉式

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

优点:使用时才初始化实例,节省资源

缺点:锁的粒度过大,导致并发度降低;如果初始化内容较多时,加载数据会变慢,影响系统性能。

3.双重检查+volatile

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

优点:1. 线程安全。在实例未空时才加锁,提高了并发度。

​ 2.使用volatile修饰变量,静止指令重排序,避免NPE。

4.静态内部类

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

优点:线程安全,懒加载

5.枚举

public enum Singleton {
    INSTANCE;
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

优点:线程安全

缺点:类加载时实例化对象,可能实例不被使用,造成内存浪费。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值