技术文摘
单例的五种手撕写法
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;
}
}
不同的单例写法各有优缺点,在实际开发中,需要根据具体的业务场景和性能要求选择合适的单例模式实现方式。掌握这些手撕写法,将有助于我们更好地设计和优化代码。
- WSL 系统更换国内源的详细方法(含固定路径与国内镜像源)
- LeetCode 前缀和示例后端算法题解详解
- BurpSuite 详尽安装与基础使用指南(已破解)
- Xmind2022 非试用版详细图文下载教程
- Mapboxgl 加载 Tiff 相关问题
- 免费内网穿透工具超好用 永久免费且不限流量
- 默克树 Merkle tree 有意思的数据结构及应用介绍
- 羊了个羊通关秘籍(多次成功入羊群)
- ABAP ALV 的常规写法与常用功能解析
- Common Lisp 命令行参数解析示例
- Dart 语言异步处理之浅析
- 为《羊了个羊》配置智能客服系统的教程
- APAP ALV 进阶写法与优化深度解析
- Google Dart 编程的语法及基本类型学习指南
- Dart String 字符串常用方法总结