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

// 功能代码

}

}

相关推荐
啦啦啦啦啦zzzz35 分钟前
设计模式:单例模式和工厂模式
c++·单例模式·设计模式·工厂模式
小白说大模型3 小时前
Python 工程化设计模式:AI 项目中的异步流水线与策略模式实战
人工智能·python·设计模式
空杆推不起4 小时前
金融数仓标准化:信贷业务 ODS/DWD/DWS/ADS/DIM 全层级建模指南
单例模式·金融
choumin6 小时前
行为型模式——中介者模式
c++·设计模式·中介者模式·行为型模式
geovindu1 天前
Java: Chain of Responsibility Pattern
java·开发语言·后端·设计模式·责任链模式·行为模式
workflower2 天前
装备企业的 AI 路线图
人工智能·深度学习·机器学习·设计模式·机器人
geovindu2 天前
CSharp:Chain of Responsibility Pattern
开发语言·后端·设计模式·c#·.net·责任链模式·行为模式
梓仁沐白2 天前
【Agent 设计模式】路由模式(Routing)
大数据·设计模式
梓仁沐白2 天前
【Agent 设计模式】多智能体协作
microsoft·设计模式·php
努力学习的廖同学2 天前
前端进阶-设计模式
设计模式