设计模式之单例模式

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

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

相关推荐
写后端的胖头鱼13 分钟前
一文详解CAS
java·jvm·spring·cas·乐观锁·自旋
鱼宵21 分钟前
Spring AI 提示词模板:{变量} 参数化 + few-shot,一条提示词反复用
java·人工智能·spring·few-shot·提示词工程·springai
蜗牛互联网26 分钟前
Python消费Responses SSE事件:增量文本、超时与取消
java·开发语言·人工智能·后端·python
wanderist.36 分钟前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
Escalating_xu2 小时前
【C 语言】深入理解指针(5):sizeof、strlen、数组名语义与指针笔试题全解析
java·c语言·开发语言
HEJOO92 小时前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
谢亮_vipxieliang2 小时前
Go Channel 高级模式——从底层原理到扇出扇入实战
java·数据库·golang
Code_Solitude2 小时前
c语言:递归
java·c语言·算法
Nebula_g2 小时前
JavaSE加强:Stream流
java·开发语言·windows·stream·javase·流
估值探索者2 小时前
【Python量化系统工程实战 #08】从脚本到生产:量化系统上线 checklist 的最小闭环
java·开发语言·jvm·python·数据挖掘·数据·股票数据api接口