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() {

// 功能代码

}

}

相关推荐
ApeAssistant1 小时前
Spring + 设计模式 (八) 结构型 - 外观模式
spring·设计模式
ApeAssistant1 小时前
Spring + 设计模式 (七) 结构型 - 装饰器模式
spring·设计模式
都叫我大帅哥2 小时前
代码界的「万能前台」:门面模式的调停艺术
java·后端·设计模式
牛奶咖啡133 小时前
学习设计模式《四》——单例模式
单例模式·设计模式·饿汉式单例·懒汉式单例·线程安全的单例·可控制实例数量的单例·何时使用单例模式
幼儿园口算大王6 小时前
单例设计模式
java·设计模式
johnrui13 小时前
JAVA设计模式:注解+模板+接口
java·windows·设计模式
天堂的恶魔94614 小时前
C++项目 —— 基于多设计模式下的同步&异步日志系统(4)(双缓冲区异步任务处理器(AsyncLooper)设计)
开发语言·c++·设计模式
侧耳倾听11115 小时前
java 设计模式之单例模式
java·单例模式·设计模式
天堂的恶魔94616 小时前
C++项目 —— 基于多设计模式下的同步&异步日志系统(5)(单例模式)
c++·单例模式·设计模式
AronTing19 小时前
装饰模式:动态扩展对象功能的优雅设计
java·后端·设计模式