单例设计模式
通过单例设计模式可以保证系统中,应用该模式的类只有一个对象实例
使用场景
- 业务系统全局只需要一个对象实例,比如发号器、redis 连接对象等
- Spring IOC 容器中Bean 默认就是单例
分类
- 懒汉式:就是懒加载,延迟创建对象
- 饿汉式:与懒汉相反,提前创建对象
实现步骤
- 私有化构造对象
- 提供获取实例的构造方法
饿汉式
public class HungrySingleton {
private static HungrySingleton singleton = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return singleton;
}
}
懒汉式
线程安全
public class LazySingleton {
private static LazySingleton singleton = null;
/**
* 第一步: 私有构造方法
*/
private LazySingleton() {}
/**
* 提供获取实例的方法 - 线程不安全
* @return
*/
public static LazySingleton getInstance() {
// 可能多个线程同时创建
if (null == singleton) {
singleton = new LazySingleton();
}
return singleton;
}
}
线程不安全
public class DCLLazySingleton {
/**
* 使用volatile
* 保证 singleton = new DCLLazySingleton(); 原子性
* 1. 在内存开辟空间给对象
* 2. 在空间内创建对象
* 3. 将对象赋值给引用变量
*
*/
private static volatile DCLLazySingleton singleton = null;
private DCLLazySingleton() {}
public static DCLLazySingleton getInstance() {
if (null == singleton) {
// 可能有多个线程进入
synchronized (DCLLazySingleton.class) {
// 所以再判断
if (null == singleton) {
singleton = new DCLLazySingleton();
}
}
}
return singleton;
}
}