Java设计模式之单例模式

本文详细介绍了Java中的单例模式实现方式,包括饿汉式、懒汉式及其线程安全性问题,以及针对懒汉式的双重检测锁DCL、静态内部类和枚举实现单例的优化方法。此外,还探讨了如何防止反射破坏单例模式,并提供了Runtime类中饿汉式单例的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式

Singleton

单例模式是一种创建型模式,通过单例模式创建的类只有一个实例存在

有时候完全只需要一个实例存在就够了,不用那么多实例存在

单例模式使用场景

  1. 频繁创建,销毁对象
  2. 创建对象耗时耗资源
  3. 工具类

饿汉式

多线程安全,常用

//饿汉式
public class SingLeton01 {
    
    //private byte[] bytes = new byte[1024];
    
    //类加载的时候就实例化这个单例
    private static final SingLeton01 INSTANCE = new SingLeton01();

    //私有化无参构造,封装好这个类 防止使用者再new而产生多个实例
    private SingLeton01(){

    }

    //拿到这个单例的方法
    public static SingLeton01 getInstance(){
        return INSTANCE;
    }

    public static void main(String[] args) {
        //测试多线程是否安全
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(()-> System.out.println(SingLeton01.getInstance())).start();
        }
    }
}

  • 优点

    • 简单常用

    • 私有化无参构造,让使用者不能再产生多的实例化

    • 类加载到内存时,实例化这个单例

    • 因为类只加载一次,所以只有这个单例,线程安全(JVM只加载一次这个类)

  • 缺点

    • 无论使用与不使用,这个单例在类加载时都被实例化了(如果这个单例类占用内存大,就很浪费)

懒汉式

多线程不安全

//懒汉式 
public class SingLeton02 {
    private SingLeton02(){

    }
    //类加载时 不初始化 所以不加final
    private static SingLeton02 INSTANCE;

    public static SingLeton02 getInstance(){
        //第一次调用这个方法时,INSTANCE为空实例化对象,之后不为空了就直接返回这个单例
        if (INSTANCE == null){
             /*try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            INSTANCE = new SingLeton02();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        //多线程测试 发现线程不安全(测不出来可以在getInstance方法中线程睡眠) 
        for (int i = 0; i < 100; i++) {
            new Thread(()-> System.out.println(SingLeton02.getInstance())).start();
        }
    }
}
  • 线程不安全原因:

    • 当线程A进入getInstance方法判断INSTANCE为空,此时线程B也进入getInstance方法并判断INSTANCE为空,然后就造成了实例多个对象,并非单例
  • 虽然解决了按需要来进行初始化的问题,但是引来了线程不安全

懒汉式加锁优化

多线程安全

既然懒汉式线程不安全,那就加锁

//懒汉式加锁优化
public class SingLeton03 {
    private SingLeton03(){

    }

    private static SingLeton03 INSTANCE;

    //因为这里是同步方法,所以锁的是SingLeton03这个Class类对象
    public synchronized static SingLeton03 getInstance(){
        if (INSTANCE == null){
            INSTANCE = new SingLeton03();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()-> System.out.println(SingLeton03.getInstance())).start();
        }
    }
}

虽然线程安全了,但是因为加了synchronized效率变低了(每次操作都要看是否加了锁等…)

懒汉式双重检测锁DCL

多线程安全

将同步方法变为同步块再优化

//懒汉式双重锁优化
public class SingLeton04 {
    private SingLeton04(){

    }
	//volatile防止指令重排序
    private volatile static SingLeton04 INSTANCE;


    public  static SingLeton04 getInstance(){
        //这里的判断条件很有必要,如果没有这条判断条件,线程一进来直接抢锁降低效率
        if (INSTANCE == null){
            synchronized (SingLeton04.class){
                if (INSTANCE == null){
                    
                    INSTANCE = new SingLeton04();
                }

            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()-> System.out.println(SingLeton04.getInstance())).start();
        }
    }
}

锁住Class对象

1.分配空间 2.执行构造,初始化 3. 指向对象

多线程中,为防止JVM重排指令(逻辑上) 应该用volatile修饰 禁止重排指令

//volatile防止重排指令
private volatile static SingLeton04 INSTANCE;

静态内部类方式

多线程安全

//静态内部类 实现懒加载,线程安全
public class SingLeton05 {
    private SingLeton05(){

    }

    //静态内部类
    public static class Inner{
        private static SingLeton05 INSTANCE = new SingLeton05();
    }

    public  static SingLeton05 getInstance(){
            return Inner.INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()-> System.out.println(SingLeton05.getInstance())).start();
        }
    }
}

Inner类在SingLeton05类内部,外部访问不了

实现了懒加载和线程安全(JVM保证单例)

枚举单例

多线程安全

effective java 作者提出

public enum SingLeton06 {
    INSTANCE;

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()-> System.out.println(SingLeton06.INSTANCE.hashCode())).start();
        }
    }
}

解决线程同步

防止反序列化

上面的写法:Java通过反射反序列化 Class对象在内存中然后再把实例new出来

枚举的反序列化不是通过反射

查看newInstance()源码 明确的说明如果是枚举去创建就会抛出非法参数异常

用枚举通过反射创建实例试试:

在这里插入图片描述

抛出的异常并不是源码中的非法参数异常

进行反编译查看字节码文件

在这里插入图片描述

实际上也是一个类继承了Enum

使用jad继续反编译

得到反编译的结果 重点看构造器

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   SingLeton06.java

package singleton;

import java.io.PrintStream;
import java.lang.reflect.Constructor;

public final class SingLeton06 extends Enum
{

    public static SingLeton06[] values()
    {
        return (SingLeton06[])$VALUES.clone();
    }

    public static SingLeton06 valueOf(String s)
    {
        return (SingLeton06)Enum.valueOf(singleton/SingLeton06, s);
    }

    private SingLeton06(String s, int i)
    {
        super(s, i);
    }

    public static void main(String args[])
        throws Exception
    {
        SingLeton06 singleton06 = INSTANCE;
        Constructor constructor = singleton/SingLeton06.getDeclaredConstructor(null);
        constructor.setAccessible(true);
        SingLeton06 singleton06_1 = (SingLeton06)constructor.newInstance(new Object[0]);
        System.out.println(singleton06);
        System.out.println(singleton06_1);
    }

    public static final SingLeton06 INSTANCE;
    private static final SingLeton06 $VALUES[];

    static 
    {
        INSTANCE = new SingLeton06("INSTANCE", 0);
        $VALUES = (new SingLeton06[] {
            INSTANCE
        });
    }
}

并没有无参构造,前面被表面给欺骗了,只有一个String,int的构造

试试这个构造

在这里插入图片描述

这才是源码中使用枚举通过反射创建对象抛出的异常

JDK中的单例模式

JDK的Runtime类中,使用了饿汉式的单例模式

  1. 私有构造器
  2. 类加载时创建实例
  3. 通过静态方法拿到实例
public class Runtime {
    //类加载的时候创建对象
    private static Runtime currentRuntime = new Runtime();
    //通过静态方法得到单例对象
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    //私有构造器
    private Runtime() {}
    //...
}    

防止反射破坏单例的方法

以饿汉式为例

通过反射可以破坏单例模式

package 创建型模式._01_singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//饿汉式
public class SingLeton01 {

    private byte[] bytes = new byte[1024];
    //类加载的时候就实例化这个单例
    private static final SingLeton01 INSTANCE = new SingLeton01();

    //私有化无参构造,封装好这个类 防止使用者再new而产生多个实例
    private SingLeton01() {

    }

    //拿到这个单例的方法
    public static SingLeton01 getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) {
        try {
            Class<SingLeton01> singLeton01Class = SingLeton01.class;
            Constructor<SingLeton01> constructor = singLeton01Class.getDeclaredConstructor(null);
            Object obj1 = constructor.newInstance();
            Object obj2 = SingLeton01.getInstance();
            System.out.println(obj1);
            System.out.println(obj2);
            System.out.println(obj1==obj2);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
/*
创建型模式._01_singleton.SingLeton01@677327b6
创建型模式._01_singleton.SingLeton01@14ae5a5
false
*/

解决反射破坏单例思路

在构造器中进行修改如果实例为不为空则在构造器中抛出异常,防止通过反射破坏单例

private SingLeton01() {
    if(SingLeton01.INSTANCE!=null){
            throw new RuntimeException("禁止破坏单例");
    }
}

/*
程序抛出的异常:
java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at 创建型模式._01_singleton.SingLeton01.main(SingLeton01.java:31)
Caused by: java.lang.RuntimeException: 禁止破坏单例
	at 创建型模式._01_singleton.SingLeton01.<init>(SingLeton01.java:17)
	... 5 more
*/
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值