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

// 功能代码

}

}

相关推荐
炎芯随笔7 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
阿沁QWQ11 小时前
单例模式的两种设计
开发语言·c++·单例模式
workflower15 小时前
使用谱聚类将相似度矩阵分为2类
人工智能·深度学习·算法·机器学习·设计模式·软件工程·软件需求
枣伊吕波17 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
lalajh18 小时前
论软件设计模式及其应用
设计模式
lgily-122520 小时前
常用的设计模式详解
java·后端·python·设计模式
周努力.2 天前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z2 天前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry2 天前
常用设计模式
设计模式
z26373056112 天前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则