工厂构造函数实现单例模式并传参

Flutter 封装请求方法类时使用了工厂构造函数的单例模式,在调试时为了按需控制请求打印日志,最好的方法就是往请求体中传参数控制,可是想了好久都不晓得怎么个传参法,后来查看 GitHub 时得到了解决方法,具体如下。

class NetUtil {
  static final NetUtil _instance = NetUtil._internal();
  static bool showLog = false;

  factory NetUtil([bool isShowLog = false]) {
    showLog = isShowLog;
    return _instance;
  }

  NetUtil._internal() {
    if (showLog) {
      // 省略无关代码
    }
  }

  Future get(String url) async {}

  Future post(String url) async {}
}

main() {
  // 调用
  NetUtil(true).get('');
}

参考

https://gist.github.com/theburningmonk/6401183#gistcomment-2903680

原文地址:https://www.cnblogs.com/teemwu/p/12716171.html