gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:34:50 27 4
gpt4 key购买 nike

我有两个类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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com