设计模式之单例模式

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

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

相关推荐
二进制person11 小时前
JavaEE初阶 --文件操作和IO
java·java-ee
@老蝴11 小时前
Java EE - 线程安全的产生及解决方法
java·开发语言·java-ee
せいしゅん青春之我11 小时前
【JavaEE初阶】网络层-IP协议
java·服务器·网络·网络协议·tcp/ip·java-ee
Han.miracle11 小时前
Java ee初阶——定时器
java·java-ee
飞鱼&12 小时前
HashMap相关问题详解
java·hashmap
lapiii35812 小时前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
白露与泡影12 小时前
面试:Spring中单例模式用的是哪种?
spring·单例模式·面试
没有bug.的程序员12 小时前
Spring Cloud Alibaba 生态总览
java·开发语言·spring boot·spring cloud·alibaba
快乐非自愿13 小时前
Java垃圾收集器全解:从Serial到G1的进化之旅
java·开发语言·python
树在风中摇曳13 小时前
Java 静态成员与继承封装实战:从报错到彻底吃透核心特性
java·开发语言