Java实现单例模式的几种方式:
1. 饿汉式(推荐,线程安全)
public class Singleton {
// 类加载时就初始化
private static final Singleton INSTANCE = new Singleton();
// 私有构造
private Singleton() {
// 防止反射攻击
if (INSTANCE != null) {
throw new RuntimeException("单例模式禁止反射创建");
}
}
public static Singleton getInstance() {
return INSTANCE;
}
}
2. 静态内部类(推荐,懒加载)
public class Singleton {
private Singleton() {
// 防止反射攻击
if (InnerHolder.INSTANCE != null) {
throw new RuntimeException("单例模式禁止反射创建");
}
}
// 静态内部类
private static class InnerHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return InnerHolder.INSTANCE;
}
}
-
懒加载:只有调用
getInstance()时才加载内部类 -
线程安全:JVM保证类加载的线程安全
3. 双重检查锁(懒加载,线程安全)
public class Singleton {
// 必须加volatile,禁止指令重排序
private static volatile Singleton instance;
private Singleton() {
// 防止反射攻击
if (instance != null) {
throw new RuntimeException("单例模式禁止反射创建");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}