单例模式
大约 1 分钟
什么是单例模式?
单例模式(Singleton pattern)是使类只有一个实例,并提供实例的全局访问点。
何时使用
- 当一个类需要控制其实例数量,仅需要唯一实例时。
- 多个类需要共享某个对象的状态时。
- 减少频繁创建和销毁资源的开销。
饿汉式
在类加载时就创建实例,线程安全,但不够灵活。
// 饿汉式单例
class EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return INSTANCE;
}
}
// 客户端
public class SingletonPatternExample {
public static void main(String[] args) {
EagerSingleton instance1 = EagerSingleton.getInstance();
EagerSingleton instance2 = EagerSingleton.getInstance();
System.out.println(instance1 == instance2); // true
}
}
懒汉式
在第一次使用时创建实例,需要处理线程安全问题。
// 懒汉式单例
class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
// 客户端
public class SingletonPatternExample {
public static void main(String[] args) {
LazySingleton instance1 = LazySingleton.getInstance();
LazySingleton instance2 = LazySingleton.getInstance();
System.out.println(instance1 == instance2); // 输出 true
}
}
登记式
使用枚举类型或静态内部类实现,线程安全且简洁。
// 使用枚举实现单例
enum EnumSingleton {
INSTANCE;
public void doSomething() {
System.out.println("Doing something...");
}
}
// 客户端
public class SingletonPatternExample {
public static void main(String[] args) {
EnumSingleton instance = EnumSingleton.INSTANCE;
instance.doSomething(); // 调用方法
}
}