饿汉模式在类加载时创建实例,由JVM保证线程安全,实现简单但可能浪费资源;2. 懒汉模式在首次调用getInstance时创建,支持延迟加载,节省内存,但需通过volatile和双重检查锁定确保线程安全;3. 两者主要区别在于实例化时机、资源利用、线程安全和性能,选择取决于是否需要延迟加载及对性能与安全的要求。
懒汉模式和饿汉模式是Java中实现单例模式的两种常见方式,它们的核心区别在于实例化时机和线程安全性。
饿汉模式在类加载时就创建实例,不管是否会被使用。
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉模式在第一次调用getInstance()方法时才创建实例。
public class Singleton {
private static v
olatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}