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

// 功能代码

}

}

相关推荐
碰大点5 小时前
数据库“Driver not loaded“错误,单例模式重构方案
数据库·sql·qt·单例模式·重构
小毛驴8505 小时前
软件单例模式
单例模式
老鼠只爱大米6 小时前
Java 设计模式之适配器模式:系统集成的万能接口
java·设计模式·适配器模式·adapter·java设计模式
o0向阳而生0o11 小时前
112、23种设计模式之命令模式(20/23)
设计模式·命令模式
将编程培养成爱好12 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极12 小时前
设计模式学习(3)-行为型模式
c++·设计模式
快乐非自愿13 小时前
常用设计模式:工厂方法模式
javascript·设计模式·工厂方法模式
guangzan20 小时前
常用设计模式:模板方法模式
设计模式
Lei_3359671 天前
[設計模式]二十三種設計模式
设计模式
吃饺子不吃馅1 天前
面试官:JWT、Cookie、Session、Token有什么区别?
前端·设计模式·面试