Dart的另类用法

1.当不知道Future什么时候返回时

复制代码
class AsyncOperation<T> {
  final Completer _completer = new Completer();

  Future doOperation() {
    _startOperation();
    return _completer.future; // Send future object back to client.
  }

  // Something calls this when the value is ready.
  void _finishOperation(T result) {
    _completer.complete(result);
  }

  // If something goes wrong, call this.
  void _errorHappened(error) {
    _completer.completeError(error);
  }

  void _startOperation() async{
    print("_startOperation:start");
    await Future.delayed(Duration(seconds: 3));
    // _finishOperation("result" as T);
    _errorHappened("error");
    print("_startOperation:end");
  }
}
View Code
复制代码

 2.Dart中的单例

复制代码
class Singleton {

  ///第一种:饿汉式
  static final Singleton _cache = Singleton._internal();
  factory Singleton.single() {
    return _cache;
  }

  ///第二种:懒加载
  static Singleton? _lazCache;
  factory Singleton.lazy(){
    return _lazCache ??= Singleton._internal();
  }

  Singleton._internal();//私有构造
}
View Code
复制代码

 

posted @   呢哇哦比较  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示