前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >设计模式之单例模式

设计模式之单例模式

作者头像
九转成圣
发布2024-04-10 16:32:12
690
发布2024-04-10 16:32:12
举报
文章被收录于专栏:csdncsdn

单例模式(Singleton)

定义

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

使用场景

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

示例代码

双重检查

代码语言:javascript
复制
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);
    }
}

静态内部类

代码语言:javascript
复制
public class Singleton5 {
    private Singleton5() { }

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

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

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

枚举

代码语言:javascript
复制
public enum Singleton6 {
    INSTANCE;
}

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-03-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单例模式(Singleton)
  • 定义
  • 使用场景
  • 示例代码
    • 双重检查
      • 静态内部类
        • 枚举
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档