Java设计模式 | 单例模式

在这里插入图片描述

单例模式介绍

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。

八种实现方式

  1. 饿汉式(静态变量)
  2. 饿汉式(静态代码块)
  3. 懒汉式(线程不安全)
  4. 懒汉式(线程安全,同步方法)
  5. 懒汉式(线程安全,同步代码块)
  6. 双重检查(双重校验锁)
  7. 静态内部类
  8. 枚举
1)饿汉式(静态变量)

步骤
  1. 构造器私有化(防止外部通过new的方式实例化对象)
  2. 类的内部创建对象
  3. 向外暴露一个静态的公共方法(getInstance)获取实例
public class SingletonTest01 {

    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

// 饿汉式(静态变量)
class Singleton {
    // 1. 构造器私有化,外部不能new
    private Singleton() {
    }

    // 2. 本类内部创建对象实例
    private final static Singleton instance = new Singleton();

    // 3. 提供一个公共的静态方法,供外部获取对象实例
    public static Singleton getInstance() {
        return instance;
    }
}

优缺点分析
  1. 优点:写法简单,在类装载的时候就完成实例化。避免了线程同步问题。
  2. 缺点:在类装载的时候就完成了实例化,没有达到Lazy Loading的效果。如果从始至终没有使用到这个实例,则会造成内存浪费。
  3. 这种基于classloader机制避免了多线程同步的同步问题,不过,instance在类装载时就实例化,在单例模式中大多数都是调用getInstance方法,但是导致类装载的原因有很多种,因此不能确定有没有其他方式(或者其他的静态方法)导致类装载,这时候初始化instance就没有达到lazy loading的效果
总结

这种单例模式可用,可能会造成内存浪费

2)饿汉式(静态代码块)
public class SingletonTest02 {

    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

// 饿汉式(静态变量)
class Singleton {
    // 1. 构造器私有化,外部不能new
    private Singleton() {
    }

    // 2. 本类内部创建对象实例
    private static Singleton instance;

    // 在静态代码块中创建单例对象
    static {
        instance = new Singleton();
    }

    // 3. 提供一个公共的静态方法,供外部获取对象实例
    public static Singleton getInstance() {
        return instance;
    }
}

优缺点分析
  1. 这种方法和静态变量的方式类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行了静态代码块中的代码,初始化类的实例。优缺点和静态变量的方式一样。
总结

这种单例模式可用,但有可能造成内存浪费

3)懒汉式(线程不安全)
public class SingletonTest03 {

    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    // 提供一个静态的公有方法,当使用到该方法时,才去创建实例,即懒汉式
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

优缺点分析
  1. 起到了lazy loading的效果,但是只能在单线程下使用
  2. 如果在多线程下,一个线程进入了if (instance == null)判断语句块,还未往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以多线程环境下不可使用该种方式
结论

在实际开发中,不可使用此方式

4)懒汉式(线程安全,同步方法)
public class SingletonTest04 {
    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    // 提供一个静态的公有方法,当使用到该方法时,才去创建实例,即懒汉式
    // 加入同步处理的代码,解决线程安全问题
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

优缺点分析
  1. 解决了线程不安全的问题
  2. 效率低,每个线程在想获取类的实例时,执行getIntance()方法都要进行同步。其实这个方法只执行一次实例化代码就够了,后面的想要获得该类实例,直接return即可。方法进行同步效率太低
结论

在实际开发中,不推荐此方式

5)懒汉式(线程安全,同步代码块)
public class SingletonTest05 {
    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

class Singleton {
    private static Singleton instance;

    private Singleton() {
    }

    // 提供一个静态的公有方法,当使用到该方法时,才去创建实例,即懒汉式
    // 加入同步处理的代码,其实并没有解决线程安全问题,因为多个线程同时执行到instance == null时,都执行了new Singleton()
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}

优缺点分析
  1. 该方式本意是对懒汉式(同步方法)的改进,因其效率低,改为同步产生实例的代码块
  2. 但是这种同步并未起到线程同步的作用,是线程不安全的。跟懒汉式(线程不安全)方式的原因一样:假如一个线程进入了if (instance == null)判断语句块,还未往下执行,另一线程也通过了此判断语句,此时便会产生多个实例
结论

在实际开发中,不使用该方式

6)双重检查(双重校验锁)
public class SingletonTest06 {
    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

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;
    }
}

优缺点分析
  1. Double-Check概念是多线程开发中常使用到的,如代码中所示,进行了两次if (instance == null)检查,这样就可以保证线程安全了
  2. 这样,实例化代码只执行了一次,后面再次访问时,判断if (instance == null),直接return实例化对象,也避免了反复进行方法同步,保证了效率
  3. 线程安全;延迟加载;效率较高

在Java中,由于JVM存在指令重排序和线程可见性的问题,当一个线程在使用一个对象的时候,另外一个线程可能会看到一个不完整的对象状态,导致程序出现一些意想不到的错误。这个问题在多线程环境下非常常见。
为了解决这个问题,Java提供了一种关键字叫做volatile,它可以禁止JVM指令重排。它可以确保变量的可见性和有序性。在多线程环境下,当一个线程修改了volatile变量时,它会立即刷新到主存中,而其他线程在访问该变量时会强制从主存中重新读取最新的值,从而避免了读取到不完整的对象状态。
在单例模式的实现中,由于instance变量在getInstance()方法中被多个线程共享,因此需要使用volatile关键字来确保变量的可见性和有序性,从而避免了多线程环境下的并发访问问题。

结论

在实际开发中,推荐使用该方式

7)静态内部类
public class SingletonTest07 {
    public static void main(String[] args) {
        // 测试,instance1和instance2是同一个对象实例,其hashcode也相同
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

class Singleton {

    // 构造器私有化
    private Singleton() {
    }

    // 写一个静态内部类,该类中有一个静态属性Singleton
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    // 提供一个静态的公有方法,直接返回Singleton.INSTANCE
    public static Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

优缺点分析
  1. 此方式采用了类装载的机制来保证初始化实例时只有一个线程
  2. 静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance()方法,才会装载SingleInstance类,从而完成Singleton的实例化
  3. 类的静态属性只会在第一次加载类的时候初始化,所以此方式,JVM帮助我们保证了线程的安全,在类进行初始化时,别的线程是无法进入的
  4. 优点:避免了线程不安全,利用静态内部类特点实现懒加载,效率高
结论

推荐使用

8)枚举
public class SingletonTest08 {

    public static void main(String[] args) {
        Singleton instance1 = Singleton.INSTANCE;
        Singleton instance2 = Singleton.INSTANCE;
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
        instance1.method();
    }
}

enum Singleton {
    INSTANCE;

    public void method() {
        System.out.println("OK!!!");
    }
}

优缺点分析
  1. 借助jdk1.5中添加的枚举来实现单例。不仅能避免多线程同步问题,还可以防止反序列化重新创建新的对象
  2. 作者提倡该方式
结论

推荐使用

单例模式JDK源码分析

  1. Runtime.java
public class Test {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
    }
}
public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    private Runtime() {}
}

可以看出Runtime类使用了单例模式(饿汉式,静态变量的方式实现的)

单例模式注意事项和细节说明

  1. 单例模式保证了系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能
  2. 当想实例化一个单例类的时候,必须要记住使用其相应的获取对象的方法,而不是使用new
  3. 单例模式使用的场景:需要频繁的进行创建和销毁的对象、创建对象时消耗过多或耗费资源过多(即重量级对象),但又经常用到的对象,工具类对象、频繁访问数据库或文件的对象(如数据源、session工厂)

反射 & 序列化攻击

反射攻击和反序列化攻击是两种常见的安全问题,都可以用来攻击单例模式的实现

反射攻击

反射攻击是指通过Java的反射机制来获取类的私有构造方法,然后通过构造方法创建类的实例对象,从而破坏单例模式的实现。由于Java的反射机制可以访问私有的构造方法,因此攻击者可以通过这种方式来创建多个实例对象,从而破坏单例模式的唯一性。

序列化攻击

反序列化攻击是指攻击者通过序列化和反序列化技术来破坏单例模式的实现。攻击者可以通过序列化和反序列化来创建多个实例对象,从而破坏单例模式的唯一性。这种攻击方式常常被用于分布式系统中,攻击者可以在一个系统中序列化一个对象,然后在另一个系统中反序列化该对象,从而创建多个实例对象。

那怎么去防止攻击呢?其实很简单, 为了防止反序列化攻击,可以在单例类中添加一个readResolve()方法,用来替换从反序列化流中反序列化出的对象,确保只有单例对象的引用被返回

    // 保护措施
    protected Object readResolve() {
        return instance;
    }

github笔记

  • 28
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值