01 单例模式
2021年5月19日 -study xdclass.net
- 备注:面试重点考查
单例:“例”是对象实例的个数,“单例”即只有一个对象实例。
通过单例模式可以保证系统中,应用该模式的类只有一个对象实例。
1 使用场景
- 业务系统全局只需要一个对象实例,比如发号器、Redis连接对象等
- Spring IoC容器中的bean默认就是单例
- Spring Boot 中的controller、service、dao层中通过
@autowire的依赖注入对象默认都是单例的
发号器:往数据库里插入数据时,可以用数据库的自增id,也可以后端通过发号器生成id。要确保生成或修改id的地方只有一个,所以要确保发号器只有一个。否则在多线程环境下可能无法保证一致性。
Redis连接对象:后端服务连接Redis,会写一个工具类,专门连接Redis。某个地方需要用到Redis时通过工具类的连接对象连接Redis,而不需要每次连接时都new一个连接对象。
@controller、@service等注解是将对象实例加入到IoC容器,默认情况下只有一个。用的时候从IoC容器中拿,用完后放回去。

2 分类
- 懒汉:就是所谓的懒加载,延迟创建对象
- 饿汉:与懒汉相反,提前创建对象
3 实现步骤
- 私有化构造函数
- 提供获取单例的方法
=-=
4 懒汉单例模式
-
懒汉单例模式的实现,(1)->(2)->(3)->(4)的演进,只有(4)才能确保性能和安全
-
(1)
public class SingletonLazy {
private static SingletonLazy instance;
/**
* 构造函数私有化
*/
private SingletonLazy() {
}
/**
* 单例对象的方法(发号器)
*/
public void process() {
System.out.println("方法调用成功");
}
/**
* 第 (1) 种方式
* 对外暴露一个方法获取类的对象
* 线程不安全,多线程下存在安全问题
*/
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
- (2)
public class SingletonLazy {
private static SingletonLazy instance;
/**
* 构造函数私有化
*/
private SingletonLazy() {
}
/**
* 单例对象的方法
*/
public void process() {
System.out.println("方法调用成功");
}
/**
* 第 (2) 种实现方式
* 通过加锁 synchronized 保证单例
* 采用 synchronized 对方法加锁有很大的性能开销
* 解决办法:锁粒度不要这么大
*/
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
- (3)
public class SingletonLazy {
private static SingletonLazy instance;
/**
* 构造函数私有化
*/
private SingletonLazy() {
}
/**
* 单例对象的方法
*/
public void process() {
System.out.println("方法调用成功");
}
/**
* 第 (3) 种实现方式
*
* DCL 双重检查锁定 (Double-Checked-Locking),在多线程情况下保持高性能
*
* 这是否安全,instance = new SingletonLazy(); 并不是原子性操作
* 1、分配空间给对象
* 2、在空间内创建对象
* 3、将对象赋值给引用instance
*
* 假如线程 1->3->2顺序(指令重排),会把值写回主内存,其他线程就会读取到 instance 最新的值,但是这个是不完全的对象
*/
public static SingletonLazy getInstance() {
if (instance == null) {
// A、B
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
- (4)
public class SingletonLazy {
/**
* 构造函数私有化
*/
private SingletonLazy() {
}
/**
* 单例对象的方法
*/
public void process() {
System.out.println("方法调用成功");
}
/**
* volatile 是 Java 提供的关键字,它具有可见性和有序性,
* <p>
* 指令重排序是 JVM 对语句执行的优化,只要语句间没有依赖,那 JVM 就有权对语句进行优化
* <p>
* 禁止了指令重排
*/
private static volatile SingletonLazy instance;
public static SingletonLazy getInstance() {
// 第一重检查
if (instance == null) {
// A、B ,锁定
synchronized (SingletonLazy.class) {
// 第二重检查
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
=-=
5 饿汉单例模式
public class SingletonHungry {
private static SingletonHungry instance = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstance() {
return instance;
}
/**
* 单例对象的方法
*/
public void process() {
System.out.println("方法调用成功");
}
}
6 懒汉与饿汉的选择
-
饿汉方式:提前创建好对象
-
优点:实现简单,没有多线程同步问题
-
缺点:不管有没使用,instance 对象一直占着这段内存
-
如何选择:
- 如果对象不大,且创建不复杂,直接用饿汉的方式即可
- 其他情况则采用懒汉实现方式
- 对于需要提高启动性能的采用懒汉,使用到的时候再创建
7 JDK源码中的单例设计模式
- JDK中
Runtime类-饿汉方式
package java.lang;
public class Runtime {
......
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
......
}
- JDK中
Desktop类-懒汉方式
package java.awt;
public class Desktop {
......
private Desktop() {
peer = Toolkit.getDefaultToolkit().createDesktopPeer(this);
}
public static synchronized Desktop getDesktop(){
if (GraphicsEnvironment.isHeadless()) throw new HeadlessException();
if (!Desktop.isDesktopSupported()) {
throw new UnsupportedOperationException("Desktop API is not " +
"supported on the current platform");
}
sun.awt.AppContext context = sun.awt.AppContext.getAppContext();
Desktop desktop = (Desktop)context.get(Desktop.class);
if (desktop == null) {
desktop = new Desktop();
context.put(Desktop.class, desktop);
}
return desktop;
}
......
}

浙公网安备 33010602011771号