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

// 功能代码

}

}

相关推荐
小码过河.17 小时前
设计模式——适配器模式
设计模式·适配器模式
钝挫力PROGRAMER18 小时前
软件工程结构型设计模式
设计模式·软件工程
老蒋每日coding19 小时前
多智能体系统工作流的设计模式与实现策略
设计模式
当战神遇到编程20 小时前
图书管理系统
java·开发语言·单例模式
Remember_99321 小时前
Java 单例模式深度解析:设计原理、实现范式与企业级应用场景
java·开发语言·javascript·单例模式·ecmascript
进击的小头21 小时前
设计模式组合应用:智能硬件控制系统
c语言·设计模式
小码过河.1 天前
设计模式——迭代器模式
设计模式·迭代器模式
琹箐1 天前
设计模式——观察者模式
观察者模式·设计模式
小码过河.2 天前
设计模式——责任链模式
设计模式·责任链模式
sg_knight2 天前
抽象工厂模式(Abstract Factory)
java·python·设计模式·抽象工厂模式·开发