简体   繁体   English

使用 noSuchMethod 在 Dart 中进行代理吗?

[英]Do proxy in Dart by using noSuchMethod?

I have many service classes which simply do the http requests, and I want to count the number of currently running http requests.我有许多服务类,它们只是执行 http 请求,我想计算当前正在运行的 http 请求的数量。 My naive idea is to use a proxy like -我天真的想法是使用像 -

int currentRunHttpRequestCounter = 0;

class MyProxy {
  noSuchMethod() {
    currentRunHttpRequestCounter+=1;
    magically_call_the_original_class(...);
    currentRunHttpRequestCounter-=1;
  }
}

However, I do not know how to magically_call_the_original_class ?但是,我不知道如何magically_call_the_original_class In other words, how do I create a proxy that passes every method call down to the original class?换句话说,如何创建一个代理,将每个方法调用向下传递到原始 class?

Thanks!谢谢!

create one abstract HTTP service with static counter.使用 static 计数器创建一个抽象 HTTP 服务。 inside that abstract service use counter and logging inside your HTTP methods.在该抽象服务内部使用计数器并在您的 HTTP 方法中记录。

Then extend that service into mocked or real service, and every time you call it it will update the counter.然后将该服务扩展为模拟或真实服务,每次调用它都会更新计数器。


class Counter {
  var getCount = 0;
}

abstract class HttpService {
  static Counter counter = Counter();
  
  Future<dynamic> get(Map<String, dynamic> query) {
    counter.getCount++;
    // use for logging ect
  }
}

class HttpMockedService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

class HttpRealService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

This is simplified solution, but you can play with many approaches to it.这是简化的解决方案,但您可以使用多种方法。

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

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