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

Android设计模式之单例模式

一、定义:

        确保一个类只有一个实例,并且自动实例化,并向整个系统提供这个实例。

二、使用场景:

        避免重复创建对象,过多消耗系统资源。

三、使用方式:

        3.1饿汉式:类加载时立即初始化,线程安全,可能会浪费资源。

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {} // 私有构造方法

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

        3.2懒汉式:需要使用实例时才进行初始化,多线程不安全。       

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

        3.3双重检查锁,DCL:使用时创建实例,使用双重锁校验,线程安全。

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

        3.4静态内部类:使用类加载机制,延迟初始化,线程安全。

public class Singleton {
    private Singleton() {}

    private static class Holder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return Holder.INSTANCE;
    }
}

        3.5枚举单例:简洁、线程安全,且能防止反射和序列化破坏单例。

public enum Singleton {
    INSTANCE;

    public void doSomething() {
        // 功能代码
    }
}


http://www.mrgr.cn/news/96339.html

相关文章:

  • 【学Rust写CAD】16 0、1、-1代数单位元(algebraic_units.rs)
  • 基于Spring Boot + Vue的银行管理系统设计与实现
  • Android设计模式之工厂方法模式
  • Chrome 开发环境快速屏蔽 CORS 跨域限制!
  • Elasticsearch 搜索高级
  • 【qt】文件类(QFile)
  • 【AI插件开发】Notepad++插件开发实践:从基础交互到ScintillaCall集成
  • 【数据结构】栈 与【LeetCode】20.有效的括号详解
  • Linux修改默认shell为zsh
  • Android 设备实现 adb connect 连接的步骤
  • Pycharm(七):几个简单案例
  • udp通信(一)
  • Oracle 23ai Vector Search 系列之2 ONNX(Open Neural Network Exchange)
  • 项目-苍穹外卖(十六) Apache ECharts+数据统计
  • 在 React 中,组件之间传递变量的常见方法
  • apache连接池机制讨论
  • Windows 我的世界 Minecraft 服务器搭建,Fabric 模组搭建教程(内网穿透)
  • 1.2-WAF\CDN\OSS\反向代理\负载均衡
  • 51c嵌入式~MOS~合集1
  • 数据库理论基础