单例模式的几种实现方式

单例模式

单例模式是一种常见的设计模式,而关于单例模式的实现又有以下几种实现方式:饿汉单例,懒汉单例,双重校验锁,静态内部类等实现

饿汉单例

该懒汉单例是线程安全的,但是存在资源浪费的情况,在程序启动时就会创建该类的实例。

java 复制代码
/**
 * @author: dlwlrma
 * @data 2025年01月15日 16:34
 * @Description 单例模式之懒汉单例
 */
public class Singleton {

    //私有静态成员变量,在使用时才会创建实例
    private static Singleton instance = new Singleton();

    //私有构造方法
    private Singleton() {
    }
    
    //唯一的公共访问点
    public static Singleton getInstance(){
        return instance;
    }
}

懒汉单例

java 复制代码
/**
 * @author: dlwlrma
 * @data 2025年01月15日 16:40
 * @Description 懒汉单例
 */
public class Singleton {
    
    //私有静态成员变量,初始化为null
    private static Singleton instance = null;
    
    //私有构造器
    private Singleton() {
        
    }
    
    //获取唯一可用实例,先判断是否已经创建实例,如果没有创建,则创建实例
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

双重校验锁(DLC)

java 复制代码
/**
 * @author: dlwlrma
 * @data 2025年01月15日 16:50
 * @Description 双重校验锁
 */
public class Singleton {
    private volatile static Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

静态内部类

java 复制代码
/**
 * @author: dlwlrma
 * @data 2025年01月15日 16:55
 * @Description 静态内部类
 */
public class Singleton{
    private Singleton(){
        
    }
    
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}
相关推荐
lUie INGA4 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
小糖学代码4 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
handler014 小时前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
geBR OTTE4 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu4 小时前
博客系统UI自动化测试报告
java
小白学大数据5 小时前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调5 小时前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳5 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木5 小时前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***5445 小时前
如何在Dev-C++中使用Clang编译器
开发语言·c++