技术文摘
单例的五种手撕写法
2024-12-30 14:56:46 小编
单例的五种手撕写法
在编程领域中,单例模式是一种常见且实用的设计模式。它确保一个类只有一个实例存在,并提供全局访问点。下面将为您详细介绍单例的五种手撕写法。
一、懒汉式(非线程安全)
这种写法在第一次调用 getInstance 方法时才创建实例,节省了资源,但在多线程环境下可能会创建多个实例。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
二、懒汉式(线程安全)
通过给 getInstance 方法加锁,保证在多线程环境下也只有一个实例被创建,但效率相对较低。
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 Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
四、双重检查锁
结合了懒汉式和线程安全的优点,通过两次判断 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;
}
}
五、静态内部类
利用 JVM 类加载机制实现线程安全和延迟加载。
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
不同的单例写法各有优缺点,在实际开发中,需要根据具体的业务场景和性能要求选择合适的单例模式实现方式。掌握这些手撕写法,将有助于我们更好地设计和优化代码。
- Docker 中安装 MongoDB 及使用 Navicat 连接的操作指南
- K8s 中 Service 查找绑定 Pod 及实现 Pod 负载均衡的办法
- Vmware 临时文件的存放路径
- Docker 中制作 tomcat 镜像及部署项目的步骤
- docker gitea drone 构建超轻量级 CI/CD 实战深度剖析
- Docker 中修改 MySQL 配置文件问题的解决之道
- CentOS 7.9 安装 docker20.10.12 流程解析
- Windows 借助 WSL2 安装 Docker 的两种方式详解
- Docker 与 Nginx 部署前端项目的详细流程记录
- Mac 利用 Docker 一键部署 Nexus3 的流程记录
- Docker Desktop 启用 Kubernetes 1.25 流程记录
- sealos 助力快速搭建 K8s 集群环境的步骤
- Linux 环境下定时自动备份 Docker 内所有 SqlServer 数据库的脚本
- 阿里云 Kubernetes 中查找镜像内 jar 包的方法(docker 查看镜像中的 jar)
- Docker 部署 openGauss 国产数据库的操作指南