设计模式之单例模式

单例模式(Singleton)

定义

保证一个类仅有一个实例,并提供一个全局访问点。

使用场景

当你希望整个系统运行期间某个类只有一个实例时候

示例代码

双重检查

java 复制代码
public class Singleton1 {
    private Singleton1() { }
    private static volatile Singleton1 instance;
    public static Singleton1 getInstance() {
        // 第一重检查 为了提高性能
        if (instance == null) {
            synchronized (Singleton1.class){
                // 第二重检查 保证线程安全
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Singleton1 instance1 = Singleton1.getInstance();
        System.out.println("instance1 = " + instance1);
        // 通过反序列化破坏
        Singleton1 instance2 = JSON.parseObject(JSON.toJSONString(instance1), Singleton1.class);
        System.out.println("instance2 = " + instance2);
        // 通过反射破坏
        Constructor<Singleton1> constructor = Singleton1.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton1 instance3 = constructor.newInstance();
        System.out.println("instance3 = " + instance3);
    }
}

静态内部类

java 复制代码
public class Singleton5 {
    private Singleton5() { }

    private static class SingletonInstance {
        private final static Singleton5 INSTANCE = new Singleton5();
    }

    public static Singleton5 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

静态内部类只有在加载的时候才会加载,且加载一次

枚举

java 复制代码
public enum Singleton6 {
    INSTANCE;
}

除枚举外其他的都可以通过反射和反序列化破坏掉

相关推荐
用户446139430274 分钟前
从单体到微服务:我们项目的拆分思路和踩坑记录
java
TDengine (老段)34 分钟前
TDengine 免费版说明
java·大数据·数据库·物联网·时序数据库·tdengine
码上有光38 分钟前
异常和智能指针
java·大数据·c++·servlet·异常·智能指针
学计算机的计算基1 小时前
操作系统内存管理全解:虚拟内存、页表、COW、malloc、OOM一篇搞定
java·笔记·算法
tachibana21 小时前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
万亿少女的梦1682 小时前
基于Spring Boot、Java与MySQL的网络订餐系统设计与实现
java·spring boot·mysql·系统设计·网络订餐
触底反弹2 小时前
🤯 面试被问 AI Workflow 和 Agent 有啥区别?3 张图 + 2 段代码讲清楚!
人工智能·设计模式·面试
咩咩啃树皮10 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
鱟鲥鳚11 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
大模型码小白12 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程