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

// 功能代码

}

}

相关推荐
geovindu18 小时前
rust:Builder Pattern
开发语言·设计模式·rust·建造者模式
小王师傅6619 小时前
【设计模式】装饰模式(三):从装饰模式看 Java 与面向对象设计(原理篇)
设计模式
Zane19941 天前
从一次支付渠道扩展需求,看懂"多用组合少用继承"到底在说什么
设计模式
geovindu1 天前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式
geovindu1 天前
sql: Data Modeling Patterns using mysql
sql·mysql·设计模式·数据库开发
sarasuki2 天前
失败重试:Agent 中指数退避的正确姿势
人工智能·设计模式·agent
Zane19942 天前
为什么你写的 Java 代码"看着面向对象、实际是面向过程"?
设计模式
geovindu2 天前
sql: Data Modeling Patterns
数据库·sql·设计模式·sqlserver
YHL4 天前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
2401_868534784 天前
网络环境规划核心考点全梳理
网络·设计模式