hi,我不是一名外包公司的员工,也不会偷吃茶水间的零食,我的梦想是能写高端CRUD
2025本人正在沉淀中… 博客更新速度++
欢迎点赞、收藏、关注,跟上我的更新节奏
当你的天空突然下了大雨,那是我在为你炸乌云
文章目录
- 一、入门
- 什么是单例模式?
- 为什么要单例模式?
- 如何实现单例模式?
- 懒汉式
- 双重检查(DCL)
- 静态内部类
- 枚举
- 二、单例模式在框架源码中的运用
- Java 标准库 RunTime类
- Spring Framework
- 三、总结
- 单例模式的优点
- 单例模式的缺点
- 单例模式的适用场景
单例模式是一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。它常用于需要全局唯一对象的场景,如配置管理、连接池等。
public class Singleton {
// 在类加载时就创建实例
private static final Singleton INSTANCE = new Singleton();
// 私有构造函数,防止外部通过 new 创建实例
private Singleton() {}
// 提供全局访问点
public static Singleton getInstance() {
return INSTANCE;
}
}
特点
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public 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;
}
}
public 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 void doSomething() {
// 业务逻辑
}
}
Runtime 类:Runtime
类是典型的单例模式实现,用于管理应用程序的运行环境。
public class Runtime {
private static final Runtime currentRuntime = new Runtime();
private Runtime() {}
public static Runtime getRuntime() {
return currentRuntime;
}
}
Runtime
实例。Spring 框架中的单例模式主要用于管理 Bean 的生命周期。
Spring 的默认 Bean 作用域:
Singleton
作用域),即每个 Spring 容器中只有一个实例。@Service
public class UserService {
// UserService 在 Spring 容器中是单例的
}
@Service
@Scope("singleton") // 默认就是单例,可以省略
public class UserService {
}
单例 Bean 的管理:
ConfigManager
)。Logger
)。DataSource
)。ThreadPool
)。CacheManager
)。Counter
)。Lock
)。DateUtils
)。StringUtils
)。ApplicationContext
。SqlSessionFactory
。