标签:占用 stat pre 单例模式 简单 on() 序列 内部类 成功
饿汉式单例
// 缺点: 在类不使用时也会加载,浪费内存
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
同步单例
// 缺点:在类创建成功后其实不需要同步,性能低
class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
双重检查锁单例
// 缺点:写法复杂,仍需要同步
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类单例
// 优点: 1.延迟初始化,不占用内存;2.无需同步,通过jvm类加载保证线程安全
class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
枚举类单例
// 优点: 写法简单,序列化安全,避免反射攻击
// 没有懒加载
public enum Singleton {
INSTANCE;
public static Singleton getInstance() {
return INSTANCE;
}
}
标签:占用 stat pre 单例模式 简单 on() 序列 内部类 成功
原文地址:https://www.cnblogs.com/bosslv/p/11351382.html