单例模式的8种写法

单例模式的8种写法

第四个和第六个更好。

第一种:饿汉式(静态常量)(可用)

/**
 * 饿汉式(静态常量)(可用)
 */
public class Singleton1 {
    private final static Singleton1 INSTANCE = new Singleton1();
    private Singleton1() {
    }
    public static Singleton1 getInstance(){
        return INSTANCE;
    }
}

第二种:饿汉式(静态代码块)(可用)

/**
 * 饿汉式(静态代码块)(可用)
 */
public class Singleton2 {
    private final static Singleton2 INSTANCE;
    static{
        INSTANCE = new Singleton2();
    }
    private Singleton2() {
    }
    public static Singleton2 getInstance(){
        return INSTANCE;
    }
}

第三种:懒汉式(线程安全)(可用,不推荐,效率太低)

/**
 * 懒汉式(线程安全)(可用,不推荐,效率太低),访问线程很多的时候不能及时得到响应
 * synchronized放在方法上,锁的范围扩大了,因为往往方法里不是所有的代码都需要同步,所以放在方法内,就可以我们自由的控制同步范围,最小化的同步范围可以提高性能
 */
public class Singleton4 {
    private static Singleton4 INSTANCE;
    private Singleton4() {
    }
    public synchronized static Singleton4 getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Singleton4();
        }
        return INSTANCE;
    }
}

第四种:双重检查(推荐面试使用

/**
 * **双重检查(推荐面试使用)
 * 优点:线程安全;延迟加载;效率较高。
 * synchronized放在方法上,锁的范围扩大了,因为往往方法里不是所有的代码都需要同步,
 * 所以放在方法内,就可以我们自由的控制同步范围,最小化的同步范围可以提高性能
 */
public class Singleton6 {
    //为什么要加volatile,是为了防止重排序,新建对象不是原子,新建一个对象它分为3步——第一步:创建一个空的Singleton6()(分配内存空间给这个对象),第二步:调用构造方法(初始化对象),第三步:将对象赋值给引用(设置引用指向分配的内存地址);
    // 但是如果进行了重排序,将第二步和第三补调换,就可能在执行构造方法之前,CPU切换到其他线程,其他线程经过第一个if非空判断,其他线程直接拿到第一个线程创建的没有初始化的线程,出现NPE的情况。
    private volatile static Singleton6 INSTANCE;
    private Singleton6() {
    }

    public static Singleton6 getInstance(){
        if(INSTANCE == null){
            synchronized (Singleton6.class){
                if(INSTANCE == null){
                    INSTANCE = new Singleton6();
                }
            }
        }
        return INSTANCE;
    }
}

第五种:静态内部内方式(可用)

/**
 * 静态内部内方式(可用)
 */
public class Singleton7 {
    private Singleton7() {
    }
    public static Singleton7 getInstance(){
        return SingletonInstance.INSTANCE;
    }

    //这个内部类和里面的INSTANCE都是静态的,JVM类加载时就保证了唯一性
    private static class SingletonInstance {
        private static final Singleton7 INSTANCE = new Singleton7();
    }
}

第六种:枚举单例(可用)属于懒加载 实现单例的最好方法

/**
 * **枚举单例(可用)
 *      属于懒加载 实现单例的最好方法
 * 优点:
 *      1. 写法简单
 *      2. 线程有保障(反编译后就是一个静态的对象)只有在第一次使用的时候才会加载进来,同样也是一种懒加载
 *      3. 避免反序列化破坏单例,避免反射攻击(是一个其他类不具备的有点)
 *
 * enum 和 INSTANCE 两个就已经实现个单例
 * 调用whatever()用:  Singleton8.INSTANCE.whatever();
 */
public enum Singleton8 {
    INSTANCE{
        protected void printTest(){
            System.out.println("print test");
        }
    };
    protected abstract void printTest();
    private Object data;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static Singleton8 getInstance(){
        return INSTANCE;
    }
}

第七种:懒汉式(线程不安全)(不推荐)

/**
 * 懒汉式(线程不安全)(不推荐)
 * 多个线程同时进入 if(INSTANCE == null){里就会出现多次创建实例
 */
public class Singleton5 {
    private static Singleton5 INSTANCE;
    private Singleton5() {
    }

    public static Singleton5 getInstance(){
        if(INSTANCE == null){
            synchronized (Singleton5.class){
                INSTANCE = new Singleton5();
            }
        }
        return INSTANCE;
    }
}

第八种:懒汉式(线程不安全)(不可用)

/**
 * 懒汉式(线程不安全)(不可用)
 */
public class Singleton3 {
    private static Singleton3 INSTANCE;
    private Singleton3() {
    }

    public static Singleton3 getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Singleton3();
        }
        return INSTANCE;
    }
}

测试反射攻击

为了验证反射攻击,将Singleton2和Singleton4的构造方法加上非空判断。

//Singleton2是饿汉式
private Singleton2() {
        if(null != INSTANCE){
            throw new RuntimeException("單例模式禁止反射調用");
        }
    }
//Singleton4是懒汉式
private Singleton4() {
        if(null != INSTANCE){
            throw new RuntimeException("單例模式禁止反射調用");
        }
    }


测试类

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //饿汉式防止反射攻击的方式
        Class s2 = Singleton2.class;
        Constructor construct = s2.getDeclaredConstructor();
        construct.setAccessible(true);//将私有构造开放

        Singleton2 newInstance = Singleton2.getInstance();
        //饿汉式通过反射获取对象,因为饿汉式是在类加载的时候实例对象的,所以如果在构造方法里判非空,此时反射获取对象就会拦截
        Singleton2 instance = (Singleton2) construct.newInstance();


          //懒汉式不能防止反射攻击的
//        Class s4 = Singleton4.class;
//        Constructor construct = s4.getDeclaredConstructor();
//        construct.setAccessible(true);//将私有构造开放
//        //懒汉式通过反射获取对象,因为懒汉式是在类加载之后实例对象的,所以就算在构造方法里判非空,此时如果反射获取对象先执行,还是会获取到对象
//        Singleton4 instance = (Singleton4) construct.newInstance();
//        Singleton4 newInstance = Singleton4.getInstance();

        System.out.println(instance);
        System.out.println(newInstance);
        System.out.println(instance == newInstance);
    }
}

饿汉式防止反射攻击的方式 运行结果

Exception in thread "main" 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 controller.singleton.Test.main(Test.java:15)
Caused by: java.lang.RuntimeException: 單例模式禁止反射調用
	at controller.singleton.Singleton2.<init>(Singleton2.java:15)
	... 5 more
	Process finished with exit code 1

测试加上标识判断后反射攻击

直接修改Singleton4 这个懒汉式,因为反射可以修改累的成员变量的值,所以判断失效

public class Singleton4 {
    private static Singleton4 INSTANCE;

    private static boolean flag = true;
    private Singleton4() {
        if(flag){
            flag = false;
        }else {
            throw new RuntimeException("單例模式禁止反射調用");
        }
    }

    public synchronized static Singleton4 getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Singleton4();
        }
        return INSTANCE;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class objectClass = Singleton4.class;
        //获取反射的构造类
        Constructor c = objectClass.getDeclaredConstructor();
        //因为构造方法时private,所以需要开放构造方法
        c.setAccessible(true);

        Singleton4 o1 = Singleton4.getInstance();

        //获取类成员变量
        Field flag = o1.getClass().getDeclaredField("flag");
        //因为flag是private的,所以需设置权限
        flag.setAccessible(true);
        //修改flag的值
        flag.set(o1,true);

        Singleton4 o2 = (Singleton4) c.newInstance();

        System.out.println(o1);
        System.out.println(o2);
        System.out.println(o1 == o2);
    }
}

运行结果

controller.singleton.Singleton4@27716f4
controller.singleton.Singleton4@8efb846
false

测试序列化破坏单例模式原理

import java.io.*;
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Singleton2 instance = Singleton2.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file") );
        oos.writeObject(instance);

        File file = new File("singleton_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        Singleton2 newInstance = (Singleton2) ois.readObject();

        System.out.println(instance);
        System.out.println(newInstance);
        System.out.println(instance == newInstance);

    }
}

运行结果(发现拿到了两个不同的实例)

controller.singleton.Singleton2@30f39991
controller.singleton.Singleton2@7c3df479
false

修复:在Singleton2类里加上下面方法,再运行发现拿到的是同一个对象。

private Object readResolve(){
        return INSTANCE;
    }
controller.singleton.Singleton2@30f39991
controller.singleton.Singleton2@30f39991
true

这是因为ObjectInputStream 的readObject()读取对象方法里有检查是否有这个方法
在这里插入图片描述
在这里插入图片描述

上篇:JVM内存结构、Java对象模型、Java内存模型(JMM)
下篇:活跃性问题(死锁)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值