proxy - 如何使用 dart 实现委托(delegate)/代理?

标签 proxy delegates dart dart-mirrors nosuchmethod

我有两个类ParserProxy ,当我从 Parser 调用方法时, 不存在,它将委托(delegate)给 Proxy类(class)。

我的代码:

class Parser {
    noSuchMethod(Invocation invocation) {
        // how to pass the `invocation` to `Proxy`???
    }
}

class Proxy {
    static String hello() { return "hello"; }
    static String world() { return "world"; }
}

当我写的时候:

var parser = new Parser();
print(parser.hello());

它将打印:
hello

最佳答案

亚历山大的回答是正确的,但我想补充一点。

我假设委托(delegate) Proxy是一个实现细节,我们不希望用户接触到它。在这种情况下,我们应该对在 parser 上调用方法的情况进行一些处理。 Proxy 不支持的.现在,如果你这样做:

void main() {
  var parser = new Parser();
  print(parser.foo());
}

你得到这个错误:

Unhandled exception:
Compile-time error during mirrored execution: <Dart_Invoke: did not find static method 'Proxy.foo'.>

我会在 noSuchMethod 中编写代码有点不同。在委派给 Proxy 之前, 我会检查 Proxy支持我将要调用的方法。如果 Proxy支持它,我会调用 Proxy 上的方法正如亚历山大在他的回答中所描述的那样。如果 Proxy不支持该方法,我会抛出 NoSuchMethodError .

这是答案的修订版:

import 'dart:mirrors';

class Parser {
  noSuchMethod(Invocation invocation) {
    ClassMirror cm = reflectClass(Proxy);
    if (cm.methods.keys.contains(invocation.memberName)) {
      return cm.invoke(invocation.memberName
          , invocation.positionalArguments
          /*, invocation.namedArguments*/ // not implemented yet
          ).reflectee;
    }
    throw new NoSuchMethodError(this,
        _symbolToString(invocation.memberName),
        invocation.positionalArguments,
        _symbolMapToStringMap(invocation.namedArguments));
  }
}


String _symbolToString(Symbol symbol) => MirrorSystem.getName(symbol);

Map<String, dynamic> _symbolMapToStringMap(Map<Symbol, dynamic> map) {
  if (map == null) return null;
  var result = new Map<String, dynamic>();
  map.forEach((Symbol key, value) {
    result[_symbolToString(key)] = value;
  });
  return result;
}

class Proxy {
  static String hello() { return "hello"; }
  static String world() { return "world"; }
}

main(){
  var parser = new Parser();
  print(parser.hello());
  print(parser.world());
  print(parser.foo());
}

这是运行此代码的输出:

hello
world
Unhandled exception:
NoSuchMethodError : method not found: 'foo'
Receiver: Instance of 'Parser'
Arguments: []

关于proxy - 如何使用 dart 实现委托(delegate)/代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442581/

相关文章:

javascript - 如何在 flutter 中检索访问 token 值

node.js - 在企业代理 Node.js 后面访问 Github

python - 使用代理时如何避免 SSL 问题?

flutter - 当在Stream上使用Distinct()时似乎无法过滤出相同的结果

iphone - [[UIApplication sharedApplication] delegate] 是怎么回事?

ios - 未调用 Swift 3 委托(delegate)函数

flutter - 是否可以将平台 View 从主机 iOS 应用程序添加到 flutter 模块 View 而不转换为插件?

nginx - NGINX 背后的 Jenkins

java - 如何为kafka客户端配置代理?

objective-c - 为什么我的委托(delegate)方法在发送给委托(delegate)后又被发送到其父 View ?