单例模式在其他框架源码中也有广泛的应用
Glide
在Glide的代码中搜索“singleton”,可以看见Glide类是典型的DCL式单例模式:
private static volatile Glide glide;
/**
* Get the singleton.
*/
@NonNull
// Double checked locking is safe here.
public static Glide get(@NonNull Context context) {
if (glide == null) {
GeneratedAppGlideModule annotationGeneratedModule =
getAnnotationGeneratedGlideModules(context.getApplicationContext());
synchronized (Glide.class) {
if (glide == null) {
checkAndInitializeGlide(context, annotationGeneratedModule);
}
}
}
return glide;
}
EventBus
EventBus曾经是Android领域事件总线最流行的框架,但2021年以后就停止更新了,不过代码也是很有参考价值的。在代码中搜索“singleton”,可以看到这一条注释:
static volatile EventBus defaultInstance;
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance;
if (instance == null) {
instance = EventBus.defaultInstance = new EventBus();
}
}
}
return instance;
}