大话设计模式——9.单例模式(Singleton Pattern)

简介

确保一个类只有一个实例,并提供全局访问点来获取该实例,是最简单的设计模式。

UML图:

单例模式共有两种创建方式:

  • 饿汉式(线程安全)

提前创建实例,好处在于该实例全局唯一,不存在线程冲突;坏处在于未使用时也会占用内存资源。

  • 懒汉式(原生写法存在线程冲突问题)

将实例的创建延迟到第一次使用时进行,相当于懒加载

创建步骤:

  • 私有化构造器
  • 提供唯一的全局访问接口
一、饿汉式
  1. 饿汉对象:
java 复制代码
public class HungrySingleton {

    // 创建实例,类加载时已经确定实例,不存在线程冲突
    private static final HungrySingleton newInstance = new HungrySingleton();

    // 私有化构造器
    private HungrySingleton() {

    }

    public void processOn() {
        System.out.println("饿汉单例模式");
    }

    /**
     * 提供对外唯一访问实例的方法
     *
     * @return
     */
    public static HungrySingleton getInstance() {
        return newInstance;
    }
}
  1. 运行
java 复制代码
public class Main {

    public static void main(String[] args) {
        HungrySingleton.getInstance().processOn();
        HungrySingleton hungrySingleton01 = HungrySingleton.getInstance();
        HungrySingleton hungrySingleton02 = HungrySingleton.getInstance();
        System.out.println(hungrySingleton02 == hungrySingleton01);
    }
}
二、懒汉式
  1. 原生写法
java 复制代码
public class LazySingleton {


    // 实例对象
    private static LazySingleton instance = null;

    private LazySingleton() {
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

存在线程安全隐患,多个线程进入可能会重复创建实例

改造

  • 方式1:同步方法
java 复制代码
public class LazySingleton {


    // 实例对象
    private static LazySingleton instance = null;

    private LazySingleton() {
    }

    /**
     * 同步锁,每次只能允许一个线程进行获取
     * @return
     */
    public static synchronized LazySingleton getInstanceSafely(){
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

ps:改方式虽然可以确保线程安全,但是由于锁的粒度较大,高并发情况下系统性能会降低。

  • 方式2:同步代码块,使用volatile禁止指令重排,确保赋值时的原子操作同时使用DCL双重检查锁定 (Double-Checked-Locking),在多线程情况下保持高性能
java 复制代码
public class LazySingleton {


    // 实例对象,禁止指令重排,确保原子操作
    private static volatile LazySingleton instance = null;

    private LazySingleton() {
    }
    
    /**
     * 同步锁,每次只能允许一个线程进行获取
     *
     * @return
     */
    public static LazySingleton getInstanceSafely02() {
        if (null == instance) {
            synchronized (LazySingleton.class) {
                // DCL双重检查锁定 
                if (null == instance) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}
总结

对象不复杂时,建议使用饿汉式。其他情况下使用懒汉式性能较好。

相关推荐
饮水桶_T8 小时前
K8s Pod 调度深度解析笔记
笔记·设计模式·电脑·ai编程·新浪微博
bossqugadw9 小时前
13 | Java | 集合框架(重点)List /Set / Map
java·单例模式·facebook·新浪微博·segmentfault
阿策小和尚9 小时前
干掉 better-sqlite3,把 5 万星的 Ghost 6.81 压成 67MB 单包跑进 Dopame OS
人工智能·设计模式·github
Thanks_ks1 天前
单例模式与工厂模式精讲:设计模式的意图、实现与在 Java 项目中的实际应用
java·spring·单例模式·设计模式·工厂模式·线程安全·面向对象设计
lcj25112 天前
【日志系统实战】同步/异步日志系统:手写日志等级模块,吃透enum class与7大分级,面试不慌
c++·设计模式·面试·c++11·日志系统
电子科技圈2 天前
UCIe桥接IP的选型与验证:行业高频问题解析
设计模式·软件工程·软件构建·设计规范
Bode_20022 天前
交互系统研究图谱
设计模式·设计方法
李航19832 天前
Codex现代风格卧室设计案例1
人工智能·python·计算机视觉·设计模式·ai
善良勤劳勇敢而又聪明的老杨2 天前
【AI编程系列】RAG 常用设计模式
设计模式·ai编程
Meteors.2 天前
Android 项目常见问题与 23 种设计模式应用对照表(含 Kotlin 示例)
android·设计模式·kotlin