按照文档理解实现单例代码如下HZPhotoProcessor单例:
static sProcessor: HZPhotoProcessor | undefined
private constructor() {
}
public static sharedProcessor(): HZPhotoProcessor | undefined {
return HZPhotoProcessor.sProcessor;
}
// 发下在entry module调用HZPhotoProcessor.sharedProcessor() 产生实例跟 sdk module 调用产生的实例不是同一个。后来发下AppStorage组件存储是应用级别的,目前的实现单例代码的方案如下,经过验证没有问题是单例
public static sharedManager(): HZCameraManager {
let instance = AppStorage.get<HZCameraManager>("HZCameraManager")
if (instance == undefined || instance == null) {
HZCameraManager.instance = new HZCameraManager();
AppStorage.setOrCreate<HZCameraManager>("HZCameraManager", HZCameraManager.instance)
instance = HZCameraManager.instance;
}
return instance;
}
这种实现方案是否是最佳实践,有没有其它的方案?
AppStorage应用全局的UI状态存储:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-appstorage-V5
是一个用于存储应用程序数据的属性包装器,它只能在主线程中使用。如果在Taskpool中尝试使用AppStorage,可能会导致数据不一致或者崩溃等问题。因此应该确保在使用AppStorage时只在主线程中操作。
如果是为了数据持久化,可以用sendablePreferences。以下的单例支持多har包和对线程的唯一性: