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

// 功能代码

}

}

相关推荐
困鲲鲲4 小时前
设计模式:中介者模式 Mediator
设计模式·中介者模式
困鲲鲲7 小时前
设计模式:状态模式 State
设计模式·状态模式
蝸牛ちゃん10 小时前
设计模式(十一)结构型:外观模式详解
设计模式·系统架构·软考高级·外观模式
weixin_4708802611 小时前
设计模式实战:自定义SpringIOC(亲手实践)
设计模式·面试·个人提升·springioc·设计模式实战·spring框架原理
阳光明媚sunny12 小时前
创建型设计模式-工厂方法模式和抽象工厂方法模式
设计模式·工厂方法模式
困鲲鲲13 小时前
设计模式:代理模式 Proxy
设计模式·代理模式
就是帅我不改16 小时前
深入实战工厂模式与观察者模式:工厂模式与观察者模式在电商系统中的应用
后端·设计模式
云中飞鸿1 天前
结合项目阐述 设计模式:单例、工厂、观察者、代理
设计模式
蝸牛ちゃん1 天前
设计模式(二十四)行为型:访问者模式详解
设计模式·系统架构·软考高级·访问者模式
zy小狮子1 天前
【设计模式系列】策略模式vs模板模式
设计模式·策略模式