设计模式之单例模式

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

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

相关推荐
22jimmy12 分钟前
JavaWeb(二)CSS
java·开发语言·前端·css·入门·基础
vvilkim3 小时前
Java主流框架全解析:从企业级开发到云原生
java·运维·云原生
MZ_ZXD0014 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
A 计算机毕业设计-小途5 小时前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设
岁忧7 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
猿究院--王升9 小时前
jvm三色标记
java·jvm·算法
妮妮学代码10 小时前
c#:TCP服务端管理类
java·tcp/ip·c#
兔老大RabbitMQ10 小时前
git pull origin master失败
java·开发语言·git
探索java11 小时前
Netty Channel详解:从原理到实践
java·后端·netty
tuokuac12 小时前
maven与maven-archetype-plugin版本匹配问题
java·maven