大话设计模式——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;
    }
}
总结

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

相关推荐
huzhongqiang9 小时前
Python 单例模式的几种实现方式:朴素才是王道
设计模式
一只叫煤球的猫13 小时前
ThreadForge 1.2.0 发布:让 Java 并发代码更好写,这次补齐了高阶编排、示例与观测能力
java·设计模式·设计
软泡芙16 小时前
【WPF 】MVVM 设计模式在 WPF 中的实战应用
设计模式·wpf
FreeGo~17 小时前
java23种设计模式示例
设计模式
ximu_polaris17 小时前
设计模式(C++)-行为型模式-命令模式
c++·设计模式·命令模式
darkhorsefly17 小时前
《智能体设计模式》
设计模式
无敌秋17 小时前
C++ 单例模式
c++·单例模式
风筝在晴天搁浅18 小时前
手撕单例模式
java·开发语言·单例模式
ximu_polaris19 小时前
设计模式(C++)-行为型模式-责任链模式
c++·设计模式·责任链模式
geovindu1 天前
go: Visitor Pattern
开发语言·设计模式·golang·访问者模式