当前位置: 首页 > news >正文

设计模式---单例模式

目录

一、五种单例模式的实现方式

        1.饿汉模式

        2.饿汉枚举类型

        3.懒汉式

        4.双检锁懒汉式

        5.内部类懒汉式

二、JDK 中单例的体现


一、五种单例模式的实现方式

        1.饿汉模式

public class Singleton1 implements Serializable {private Singleton1() {if (INSTANCE != null) {throw new RuntimeException("单例对象不能重复创建");}System.out.println("private Singleton1()");}private static final Singleton1 INSTANCE = new Singleton1();public static Singleton1 getInstance() {return INSTANCE;}public static void otherMethod() {System.out.println("otherMethod()");}public Object readResolve() {return INSTANCE;}
}
  • 构造方法抛出异常是防止反射破坏单例

  • readResolve() 是防止反序列化破坏单例

        2.饿汉枚举类型

public enum Singleton2 {INSTANCE;private Singleton2() {System.out.println("private Singleton2()");}@Overridepublic String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}public static Singleton2 getInstance() {return INSTANCE;}public static void otherMethod() {System.out.println("otherMethod()");}
}
  • 枚举饿汉式能天然防止反射、反序列化破坏单例

        3.懒汉式

public class Singleton3 implements Serializable {private Singleton3() {System.out.println("private Singleton3()");}private static Singleton3 INSTANCE = null;// Singleton3.classpublic static synchronized Singleton3 getInstance() {if (INSTANCE == null) {INSTANCE = new Singleton3();}return INSTANCE;}public static void otherMethod() {System.out.println("otherMethod()");}}
  • 其实只有首次创建单例对象时才需要同步,但该代码实际上每次调用都会同步

  • 因此有了下面的双检锁改进

        4.双检锁懒汉式

public class Singleton4 implements Serializable {private Singleton4() {System.out.println("private Singleton4()");}private static volatile Singleton4 INSTANCE = null; // 可见性,有序性public static Singleton4 getInstance() {if (INSTANCE == null) {synchronized (Singleton4.class) {if (INSTANCE == null) {INSTANCE = new Singleton4();}}}return INSTANCE;}public static void otherMethod() {System.out.println("otherMethod()");}
}

为何必须加 volatile:

  • INSTANCE = new Singleton4() 不是原子的,分成 3 步:创建对象、调用构造、给静态变量赋值,其中后两步可能被指令重排序优化,变成先赋值、再调用构造

  • 如果线程1 先执行了赋值,线程2 执行到第一个 INSTANCE == null 时发现 INSTANCE 已经不为 null,此时就会返回一个未完全构造的对象

        5.内部类懒汉式

public class Singleton5 implements Serializable {private Singleton5() {System.out.println("private Singleton5()");}private static class Holder {static Singleton5 INSTANCE = new Singleton5();}public static Singleton5 getInstance() {return Holder.INSTANCE;}public static void otherMethod() {System.out.println("otherMethod()");}
}
  • 避免了双检锁的缺点

二、JDK 中单例的体现

  • Runtime 体现了饿汉式单例

  • Console 体现了双检锁懒汉式单例

  • Collections 中的 EmptyNavigableSet 内部类懒汉式单例

  • ReverseComparator.REVERSE_ORDER 内部类懒汉式单例

  • Comparators.NaturalOrderComparator.INSTANCE 枚举饿汉式单例

http://www.lryc.cn/news/328146.html

相关文章:

  • HarmonyOS 应用开发之启动/停止本地PageAbility
  • BaseDao封装增删改查
  • Redis入门到实战-第十三弹
  • 深度学习InputStreamReader类
  • 2023年后端面试总结
  • axios实现前后端通信报错Unsupported Media
  • 网络套接字补充——TCP网络编程
  • Nginx-记
  • JS面试题:call,apply,bind区别
  • Charles抓包配置代理手机连接
  • NA555、NE555、SA555和SE555系列精密定时器
  • 黑马鸿蒙笔记2
  • 微信小程序uniapp+vue3+ts+pinia的环境搭建
  • MongoDB聚合运算符:$let
  • HarmonyOS像素转换-如何使用像素单位设置组件的尺寸。
  • 【前端面试3+1】05v-if和v-show的区别、v-if和v-for能同时使用吗、Vuex是什么?【合并两个有序链表】
  • Unity WebRequest 变得简单
  • vue 窗口内容滚动到底部
  • 代码随想录算法训练营Day38|LC509 斐波那契数列LC70 爬楼梯LC746 使用最小花费爬楼梯
  • Qt5.14.2 大神的拖放艺术,优雅而强大的交互体验
  • python3将exe 转支持库错误 AssertionError: None does not smell like code
  • [EFI]Dell Inspiron 15 5567 电脑 Hackintosh 黑苹果efi引导文件
  • 大学 Python 程序设计实验报告:判断密码是否符合要求
  • 基于SpringBoot的农产品直卖平台
  • DevSecOps平台架构系列-微软云Azure DevSecOps平台架构
  • 操作系统:管程与进程通信机制解析
  • inno setup 卸载程序 删除整个安装目录
  • 【Vue3源码学习】— CH2.5 reactiveEffect.ts:Vue 3响应式系统的核心
  • K8S的mountPath和subPath
  • notepad++里安装32位和64位的16进制编辑器Hex-Editor