设计模式之单例模式

单例模式(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;
}

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

相关推荐
2601_96207397几秒前
苍穹外卖-day07(Spring Cache & 购物车业务逻辑)
java·后端·spring
顶点多余3 分钟前
算法哪些事儿---2
java·开发语言
深入云栈30 分钟前
CompleteFuture VS CompletableFuture:Netty 为何自研 Future
java·架构
choumou_M1 小时前
SpringBoot_7:用户资源的上传与修改
java·spring boot·后端
user_admin_god1 小时前
一体化数据归集接口详细设计说明
java·大数据·spring boot·后端·spring
LlmCraft|大模型工程实践2 小时前
08. Docker Compose 一键编排:多容器应用的指挥家
java·spring cloud·eureka
珍珠先生2 小时前
第14章 设计模式入门:单例、工厂、建造者与代理
java
坐吃山猪2 小时前
JDK 8 到 JDK 21 新特性知识要点
java·开发语言·windows
坐吃山猪2 小时前
【多线程】FutureTask多线程底层实现
java·开发语言·数据库
weixin199701080162 小时前
[特殊字符]《从0到1:闲鱼开放平台授权登录 + AccessToken 刷新 + 聚石塔部署完整链路》(附Python源码)
java·数据库·python