1.什么是单例模式
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
2.单例模式所解决的问题
单例模式主要解决了一个全局使用的类频繁地创建与销毁而过多的占用系统资源的问题
3.单例模式实现方式
3.1 懒汉式(线程不安全)
懒加载 | 线程安全 |
---|---|
是 | 否 |
public class LazySingletonTest {
private static LazySingletonTest instance;
/**
* 构造方法私有化,禁止外部实例化
*/
private LazySingletonTest(){
}
/**
* 提供全局唯一的访问入口
* @return 实例
*/
public static LazySingletonTest getInstance(){
if(instance == null){
instance = new LazySingletonTest();
}
return instance;
}
}
通过以下代码测试两次调用是否是同一个对象
public static void main(String[] args) {
LazySingletonTest instance = LazySingletonTest.getInstance();
LazySingletonTest instance1 = LazySingletonTest.getInstance();
System.out.println(instance == instance1);
}
结果为:true
但是该方法线程不安全,因为在getInstance()方法中存在判断,在多线程环境下就可能会导致多次创建对象
public class LazySingletonTest {
private static LazySingletonTest instance;
/**
* 构造方法私有化,禁止外部实例化
*/
private LazySingletonTest(){
}
/**
* 提供全局唯一的访问入口
* @return 实例
*/
public static LazySingletonTest getInstance(){
if(instance == null){
try {
//让其睡眠一会儿以模拟高并发环境
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingletonTest();
}
return instance;
}
public static void main(String[] args) {
new Thread(()->{
System.out.println(LazySingletonTest.getInstance());
}).start();
new Thread(()->{
System.out.println(LazySingletonTest.getInstance());
}).start();
}
}
结果为
LazySingletonTest@54437fbd
LazySingletonTest@79a2688b
明显两次拿到了两个不一样的对象,这就和单例模式的定义相违背了。
3.2 懒汉式(线程安全)
懒加载 | 线程安全 |
---|---|
是 | 是 |
我们只需要在getInstance()方法上加上synchronized关键字,即可保证两次拿到的
public synchronized static LazySingletonTest getInstance(){
if(instance == null){
try {
//让其睡眠一会儿以模拟高并发环境
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingletonTest();
}
return instance;
}
使用相同的测试方法结果为
LazySingletonTest@6e4b852a
LazySingletonTest@6e4b852a
此方法虽然保证了线程安全,但是由于加了锁则会导致性能较低
3.3 饿汉式
懒加载 | 线程安全 |
---|---|
否 | 是 |
public class LazySingletonTest {
private static LazySingletonTest instance = new LazySingletonTest();
/**
* 构造方法私有化,禁止外部实例化
*/
private LazySingletonTest(){
}
/**
* 提供全局唯一的访问入口
* @return 实例
*/
public static LazySingletonTest getInstance(){
return instance;
}
}
饿汉式很简单粗暴,使用静态属性直接创建,这使得对象在类加载的时候就被创建。
该方式的优点在于实现简单,且线程安全;缺点在于类加载时就初始化,浪费内存。
3.4 双检锁/双重校验锁(DCL,即 double-checked locking)
懒加载 | 线程安全 |
---|---|
是 | 是 |
public class LazySingletonTest {
private static LazySingletonTest instance ;
/**
* 构造方法私有化,禁止外部实例化
*/
private LazySingletonTest(){
}
/**
* 提供全局唯一的访问入口
* @return 实例
*/
public static LazySingletonTest getInstance(){
if(instance == null){
//将锁的粒度降低,当实例被创建完成之后,就不会再去获取锁,性能得以提升
synchronized (LazySingletonTest.class){
if(instance == null){
instance = new LazySingletonTest();
}
}
}
return instance;
}
}
DCL是对线程安全的懒汉式的改进,之前的懒汉式每次进入判断前都需要加锁,无论对象是不是已经被创建了都要先拿到锁,性能在多线程环境下一直很低,而DCL将锁的粒度降低,先判断实例是否已被实例化,然后再加锁,然后再判断,这使得性能损耗仅仅缩小在实例被创建的时候,一旦实例创建完成,将不会再去加锁,后续性能得以提升。
3.5 登记式/静态内部类
懒加载 | 线程安全 |
---|---|
是 | 是 |
public class LazySingletonTest {
/**
* 静态内部类
*/
private static class SingletonHolder {
private static final LazySingletonTest INSTANCE = new LazySingletonTest();
}
/**
* 构造方法私有化
*/
private LazySingletonTest (){}
/**
* 访问入口
* @return 实例
*/
public static LazySingletonTest getInstance() {
return SingletonHolder.INSTANCE;
}
}
静态内部类方式不用加锁,能兼顾懒加载和线程安全,似乎已经是最好的单例模式实现方式,但是其依然有缺点—反射攻击和反序列化攻击,反射攻击表现在其通过反射的方式实例化的对象和通过唯一访问入口拿到的对象不是同一个,反序列化攻击表现在其将创建的对象序列化之后在反序列化回对应实例,对象不再是同一个了。
测试如下:
引入依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
该依赖有序列化和反序列化工具。再让类实现序列化接口
public class LazySingletonTest implements Serializable {
。。。
}
再使用以下代码进行测试
public static void main(String[] args) throws IllegalAccessException,
InvocationTargetException, InstantiationException, NoSuchMethodException {
//反射攻击测试
LazySingletonTest instance = LazySingletonTest.getInstance();
Constructor<LazySingletonTest> singletonTestConstructor = LazySingletonTest.class.getDeclaredConstructor();
singletonTestConstructor.setAccessible(true);
LazySingletonTest lazySingletonTest = singletonTestConstructor.newInstance();
System.out.println(instance == lazySingletonTest);
//反序列化测试
byte[] serialize = SerializationUtils.serialize(instance);
LazySingletonTest instance2 = SerializationUtils.deserialize(serialize);
System.out.println(instance == instance2);
}
测试结果为:
false
false
实例不是同一个 这就违背了单例模式的定义。
其实不止静态内部类有这种情况,因为都是通过类的方式来实现的单例模式,之前的所有方式都有这种风险。
3.6 枚举
Joshua Bloch说:“单元素的枚举类型已经成为实现Singleton的最佳方法”
懒加载 | 线程安全 |
---|---|
否 | 是 |
public enum LazySingletonTest implements Serializable {
/**
* 实例
*/
INSTANCE;
public LazySingletonTest getInstance() {
return INSTANCE;
}
}
单例模式的实现既简单又能抵抗反序列化和反射攻击。这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。
我们来试试看对其进行上诉反序列化攻击和反射攻击会有怎样的表现
首先编写反射攻击测试方法
public static void main(String[] args) throws IllegalAccessException,
InvocationTargetException, InstantiationException, NoSuchMethodException {
//反射攻击测试
LazySingletonTest instance = LazySingletonTest.INSTANCE;
Constructor<LazySingletonTest> singletonTestConstructor = LazySingletonTest.class.getDeclaredConstructor();
singletonTestConstructor.setAccessible(true);
LazySingletonTest lazySingletonTest = singletonTestConstructor.newInstance();
System.out.println(instance == lazySingletonTest);
}
最后显示在执行过程中抛出异常NoSuchMethodException,这样就能限制其通过反射的方式来创建实例,其实其他单例模式的实现方法也可以手动实现这种效果。《effective java》中只简单的提了几句话:“享有特权的客户端可以借助AccessibleObject.setAccessible方法,通过反射机制调用私有构造器。如果需要低于这种攻击,可以修改构造器,让它在被要求创建第二个实例的时候抛出异常。我们可以简单的实现一下
private static LazySingletonTest instance ;
/**
* 构造方法私有化,禁止外部实例化
*/
private static int num = 0;
private LazySingletonTest() throws NoSuchMethodException {
if(num == 0){
num++;
}else{
throw new NoSuchMethodException();
}
}
/**
* 提供全局唯一的访问入口
* @return 实例
*/
public static LazySingletonTest getInstance() throws NoSuchMethodException {
if(instance == null){
instance = new LazySingletonTest();
}
return instance;
}
这里我们简单的实现了一下,使用了一个静态变量作为构造器的计数器,当构造器不等于0时证明已是第二次操作,我们抛出异常,最后也实现了和枚举相似功能。这里枚举类里为什么使用反射会抛出异常的内部原因这里就不做过多的阐述了,有兴趣的童鞋可以访问下面网址进行了解。
https://www.cnblogs.com/chiclee/p/9097772.html
那么反序列化攻击呢,我们测试一下
public static void main(String[] args) {
//反序列化测试
LazySingletonTest instance = LazySingletonTest.INSTANCE;
byte[] serialize = SerializationUtils.serialize(instance);
LazySingletonTest instance2 = SerializationUtils.deserialize(serialize);
System.out.println(instance == instance2);
}
最后结果为:true。表示两个实例是同一个。
对比以上几种单例模式的实现方法,相信同学们应该能明白了为什么Joshua Bloch说的“单元素的枚举类型已经成为实现Singleton的最佳方法”了吧