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

// 功能代码

}

}

相关推荐
阿波罗尼亚1 小时前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
canonical_entropy4 小时前
模型驱动架构的数学内核:统一生成与演化的 Y = F(X) ⊕ Delta 不变式
数学·设计模式·架构
小毛驴8504 小时前
软件设计模式-代理模式
设计模式·系统安全·代理模式
雨中飘荡的记忆20 小时前
工厂模式详解
设计模式
Charles_go1 天前
C#42、什么是建造者设计模式
设计模式
烤麻辣烫1 天前
23种设计模式(新手)-3接口隔离原则
java·开发语言·学习·设计模式·intellij-idea
e***U8201 天前
算法设计模式
算法·设计模式
颜酱1 天前
理解编程的设计模式(前端角度)
设计模式
ZHE|张恒1 天前
设计模式(五)原型模式 — 通过克隆快速复制对象,避免复杂初始化
设计模式·原型模式
敖云岚2 天前
【设计模式】简单易懂的行为型设计模式-策略模式
设计模式·策略模式