ToB企服应用市场:ToB评测及商务社交产业平台

标题: 设计模式---单例模式 [打印本页]

作者: 盛世宏图    时间: 2022-9-23 22:08
标题: 设计模式---单例模式
简述

话不多说,直接看实现方案例。
实现案例

饿汉式

项目启动时加载
  1. public class Test {
  2.     private static Test ins = new Test();
  3.     public static Test instance() {
  4.         return ins;
  5.     }
  6. }
复制代码
在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。
懒汉式

懒加载,在使用时才被加载
  1. public class Test {
  2.     private static Test ins;
  3.     public static synchronized Test instance() {
  4.         if (ins == null) ins = new Test();
  5.         return ins;
  6.     }
  7. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用synchronized方法 → 性能下降
懒汉式(优化版)

懒加载,在使用时才被加载(解决并发的性能问题)
  1. public class Test {
  2.     private static Test ins;
  3.     public static Test instance() {
  4.         if (ins == null) {
  5.             synchronized (Test.class) {
  6.                 if (ins == null) ins = new Test();
  7.             }
  8.         }
  9.         return ins;
  10.     }
  11. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用双重判断方法 → 相对优化前性能提升
不推荐使用
静态内部类(懒汉式)

懒加载,在使用时才会被加载(无并发性能问题)
  1. public class Test {
  2.     private static Singleton {
  3.         private static final Test ins = new Test();
  4.     }
  5.     public static Test instance() {
  6.         return Singleton.ins;
  7.     }
  8. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
推荐使用
枚举(饿汉式)
  1. public enum Test {
  2.     INSTANCE;
  3.     public static Test instance() {
  4.         return INSTANCE;
  5.     }
  6. }
复制代码
在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。
推荐使用
总结

优点

缺点

适用场景


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4