单例模式的实现方式
懒汉模式(Lazy Initialization)
懒汉模式在第一次调用getInstance()方法时才创建实例,实现了延迟加载。但需要注意的是,在多线程环境下,懒汉模式可能会存在线程安全问题。通常,可以通过添加synchronized关键字来确保线程安全,但这会牺牲一定的性能。
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
饿汉模式(Eager Initialization)
饿汉模式在类加载时就完成了实例的创建,因此是线程安全的,但可能会导致资源浪费,因为无论是否使用,实例都会被创建。
public class EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
静态内部类
静态内部类结合了懒汉模式和饿汉模式的优点,它利用了类加载器