当在 Spring Boot 中使用单例模式时,我们可以通过不同的方式来实现多种单例模式。以下是几种常见的实现方式: 1. 饿汉式单例模式(Eager Initialization):
@Component
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {
// 私有构造方法
}
public static EagerSingleton getInstance() {
return instance;
}
public void doSomething() {
// 单例对象的方法
}
}
在饿汉式单例模式中,实例在类加载时就被创建,因此可以保证线程安全。通过将类注解为 @Component
,Spring Boot 将会自动扫描并创建该单例对象。
2. 懒汉式单例模式(Lazy Initialization):
@Component
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {
// 私有构造方法
}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
public void doSomething() {
// 单例对象的方法
}
}
懒汉式单例模式在首次调用 getInstance()
方法时才创建实例。通过添加 synchronized
关键字,可以确保线程安全。但是由于每次调用 getInstance()
都需要同步,可能会影响性能。
3. 双重检查锁单例模式(Double-Checked Locking):
@Component
public class DoubleCheckedSingleton {
private volatile static DoubleCheckedSingleton instance;
private DoubleCheckedSingleton() {
// 私有构造方法
}
public static DoubleCheckedSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckedSingleton.class) {
if (instance == null) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}
public void doSomething() {
// 单例对象的方法
}
}
双重检查锁单例模式在首次调用 getInstance()
方法时才创建实例,并通过双重检查来确保线程安全。使用 volatile
关键字可以防止指令重排序带来的问题。
以上是几种常见的单例模式实现方式,你可以根据具体的需求选择适合的方式。无论使用哪种方式,记得将类注解为 @Component
,以便 Spring Boot 可以自动扫描并创建单例对象。