简体   繁体   English

Dart 中的 Lazy Singleton 与 Singleton

[英]Lazy Singleton vs Singleton in Dart

I'm using the get_it package and you get two options for registering Singletons, lazy and I guess "regular" ( GetIt.instance.registerLazySingleton and GetIt.instance.registerSingleton respectively) Here's one of the classes that's registered as a plain Singleton:我正在使用get_it包,你有两个选项来注册单身人士,懒惰和我猜是“常规”(分别是GetIt.instance.registerLazySingletonGetIt.instance.registerSingleton )这是注册为普通单身人士的类之一:

class AndroidDetails {
  static final DeviceInfoPlugin _deviceInfoPlugin = DeviceInfoPlugin();
  Map<String, dynamic> _deviceData = {};

  AndroidDetails() {
    _init().then((_) => getIt.signalReady(this));
  }

  Future<void> _init() async {
    try {
      AndroidDeviceInfo _deviceInfo = await deviceInfoPlugin.androidInfo;
      _deviceData = _getDeviceData(_deviceInfo);
    } on PlatformException {
      _deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.',
      };
    }
  }

  Map<String, dynamic> _getDeviceData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      'version.sdkInt': build.version.sdkInt,
    };
  }

  bool canChangeStatusBarColor() {
    if (_deviceData.isNotEmpty) {
      return _deviceData['version.sdkInt'] >= 21;
    }
    return null;
  }

  bool canChangeNavbarIconColor() {
    if (_deviceData.isNotEmpty) {
      return _deviceData['version.sdkInt'] >= 27;
    }
    return null;
  }
}

How it's registered:它是如何注册的:

// main.dart
getIt.registerSingleton<AndroidDetails>(AndroidDetails(), signalsReady: true);

My question is, what's the difference between a "normal" Singleton and a Lazy Singleton in Dart & the get_it package?我的问题是,Dart 和 get_it 包中的“普通”单身人士和懒惰单身人士有什么区别?

Both are Singletons .两者都是Singletons But LazySingleton refers to a class whose resource will not be initialised until its used for the 1st time.但是LazySingleton指的是一个类,它的资源在第一次使用之前不会被初始化。 It's generally used to save resources and memory.它通常用于节省资源和内存。

"Lazy" refers to initiating resources at the time of the first request instead at the time of declaration. “懒惰”是指在第一次请求时而不是在声明时启动资源。 More reading on the concept is here: https://en.wikipedia.org/wiki/Lazy_initialization关于这个概念的更多阅读在这里: https : //en.wikipedia.org/wiki/Lazy_initialization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM