gpt4 book ai didi

java - 单例 - 实例化类的最佳方式

转载 作者:行者123 更新时间:2023-11-30 10:48:17 25 4
gpt4 key购买 nike

我正在查看 Telegrams 的 Messenger 源代码,我注意到它们的单例类都在其 getInstance 方法上使用局部变量,如下所示。例如,在他们的 Android GitHub repo 上, 上课 NotificationsController.java他们有以下内容:

private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
NotificationsController localInstance = Instance;
if (localInstance == null) {
synchronized (MessagesController.class) {
localInstance = Instance;
if (localInstance == null) {
Instance = localInstance = new NotificationsController();
}
}
}
return localInstance;
}

我不完全确定本地变量“localInstance”的用途是什么。谁能准确解释“localInstance”变量的用途是什么?没有它就不能实现同样的目标吗,就像下面的代码一样?

private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
if (Instance == null) {
synchronized (MessagesController.class) {
if (Instance == null) {
Instance = new NotificationsController();
}
}
}
return Instance;
}

最佳答案

这样做是出于性能原因。

考虑变量已初始化的最常见场景。编写的代码将读取 volatile 变量一次并返回值。你的版本会读两遍。由于 volatile 读取会带来轻微的性能成本,因此使用局部变量会更快。

因为在您的情况下,延迟初始化的变量是静态的,所以最好使用 holder class 惯用语。参见 this answer举个例子。

关于java - 单例 - 实例化类的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35857270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com