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

// 功能代码

}

}

相关推荐
DKPT1 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
缘来是庄8 小时前
设计模式之中介者模式
java·设计模式·中介者模式
GodKeyNet12 小时前
设计模式-责任链模式
java·设计模式·责任链模式
想躺平的咸鱼干14 小时前
Volatile解决指令重排和单例模式
java·开发语言·单例模式·线程·并发编程
摘星编程16 小时前
深入理解责任链模式:从HTTP中间件到异常处理的实战应用
http·设计模式·中间件·责任链模式·实战应用
鼠鼠我呀218 小时前
【设计模式04】单例模式
单例模式·设计模式
缘来是庄1 天前
设计模式之访问者模式
java·设计模式·访问者模式
hqxstudying1 天前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安1 天前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie88891 天前
浅谈几种js设计模式
开发语言·javascript·设计模式