什么是单例模式
一个类只允许创建一个实例对象,并提供访问其唯一的对象的方式。这个类就是一个单例类,这种设计模式叫作单例模式。
单例模式的特点
- 单例类只能有一个实例
- 单例类必须自己创建自己的唯一实例
- 单例类必须给所有其他对象提供这一实例的访问
应用场景
- 全局唯一类
- 序列号生成器
常见形式
饿汉式和懒汉式
饿汉式和懒汉式的区别
- 饿汉式是类一旦加载,就把单例初始化完成,保证 getInstance() 方法被调用时的时候,单例已经初始化完成,可以直接使用。
- 懒汉式比较懒,只有当被调用 getInstance() 方法时,才会去初始化这个单例。
线程安全问题
- 饿汉式,在被调用 getInstance() 方法时,单例已经由 jvm 加载初始化完成,所以并发访问 getInstance() 方法返回的都是同一实例对象,线程安全。
- 懒汉式,要保证线程安全,可以有以下几种方式:
- 给静态 getInstance() 方法加锁,性能差
- getInstance() 方法双重检查给类加锁后创建对象(以上两种低版本 JDK,由于指令重排,需要加 volatile 关键字,否则创建出多个对象;JDK 1.5 内存模型加强后解决了对象 new 操作和初始化操作的原子性问题)
- 通过静态内部类实现
- 通过枚举实现
实例代码
饿汉式
/**
* @author wxj
* @date 2021年07月17日 13:04
*/
public class TestSingleton1{
private static final TestSingleton1 instance = new TestSingleton1();
private TestSingleton1(){}
private static TestSingleton1 getInstance(){
return instance;
}
}
懒汉式
/**
* 考虑多线程并发,线程不安全。
* @author wxj
* @date 2021年07月17日 13:17
*/
public class TestSingleton2 {
private static TestSingleton2 instance;
private TestSingleton2(){}
private static TestSingleton2 getInstance(){
if (instance == null){
instance = new TestSingleton2();
}
return instance;
}
}
/**
* 单例模式 懒汉式-加锁
* @author wxj
* @date 2021年07月17日 13:24
*/
public class TestSingleton3 {
private static volatile TestSingleton3 instance;
private TestSingleton3(){}
public static synchronized TestSingleton3 getInstance(){
if (instance == null){
instance = new TestSingleton3();
}
return instance;
}
}
/**
* 懒汉式-双重检查 + 对类加锁
* @author wxj
* @date 2021年07月17日 13:31
*/
public class TestSingleton4 {
private static volatile TestSingleton4 instance;
private TestSingleton4(){}
public static TestSingleton4 getInstance(){
if (instance == null){
synchronized (TestSingleton4.class){
if (instance == null){
instance = new TestSingleton4();
}
}
}
return instance;
}
}
/**
* 懒汉式-静态内部类
* @author wxj
* @date 2021年07月17日 13:34
*/
public class TestSingleton5 {
private static class SingletonHolder{
private static final TestSingleton5 instance = new TestSingleton5();
}
private TestSingleton5(){}
public static TestSingleton5 getInstance(){
return SingletonHolder.instance;
}
}
/**
* 懒汉式-枚举,id生成器
* @author wxj
* @date 2021年07月17日 13:37
*/
public enum TestSingleton {
INSTANCE;
private AtomicLong id = new AtomicLong(0);
public long getId(){
return id.incrementAndGet();
}
}
实现选择建议
- 没有特殊要求的情况下,优先选择 TestSingleton1 饿汉式。提前初始化好对象,虽然因此占用提前了资源和内存,但避免了懒加载过程中程序内存不足,超时等问题。
- 有其他特殊要求,使用 TestSingleton4 双重检查 + 对类加锁的方法
- 明确要求懒加载,可以使用 TestSingleton5 静态内部类的方式