什么是单例模式(What)
在进程中,一个类只允许创建一个对象
为什么要使用单例模式(Why)
- 解决资源冲突
- 数据只需要存在一份
单例模式的实现方式(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;
}
}
优点:线程安全
缺点:类加载时实例化对象,可能实例不被使用,造成内存浪费。