[英]Instantiating a generic class in dart
我已經使用typedef查看了stackoverflow上的示例,但看起來它主要用於回調,因此不確定它是否與我正在處理的內容相關。 我正在使用執行RPC的泛型實現一個類...
abstract class Message {
int created = new DateTime.now().millisecondsSinceEpoch;
Map map = new Map();
Map toJson();
void fromJson(String json){
map = JSON.decode(json);
this.created = map["created"];
}
String toString() {
return JSON.encode(this);
}
Message(){
map["created"] = created;
}
}
___Request和___Response都擴展了消息:
import 'Message.dart';
class TestResponse extends Message {
String test;
String message;
Map toJson() {
map["test"] = this.test;
return map;
}
fromJson(String json) {
super.fromJson(json);
this.test = map["test"];
this.message = map["message"];
}
}
現在,當我嘗試執行隱藏發送和接收消息的所有樣板的通用RPC類時,我需要創建響應類的新實例以將其發送回去。 (我本來希望做RPC.submit,但這給了我一個錯誤,說靜態靜態成員不能引用類型參數,所以我的另一個選擇是濫用構造函數語法,例如RPC.submit(json,uri).getResponse ()...)
import 'package:http/browser_client.dart';
import 'Message.dart';
class RPC<REQ extends Message, RES extends Message> {
RES submit(REQ req, String uri){
var client = new BrowserClient();
var url = "http://localhost:9090/application-api" + uri;
RES res = new RES(); // <----- can't do this
client.post(url, body: req.toString()).then((response){
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
res.fromJson(response.body);
});
return res;
}
}
在我的提交方法中,我顯然可以傳入一個“RES res”的實例並且只是使用它,但是我希望它可以在通用RPC中完成而不需要太多額外的樣板,是否在某種程度上可能在dart中?
我在類似情況下所做的是創建一個靜態映射,將類型映射到閉合構造函數。 我使用消息類型初始化映射,並為每個創建該類型的新實例的閉包。 然后我使用type參數查找閉包並調用返回的閉包來獲取一個新實例。
var factories = {
'A': () => new A(),
'B': () => new B(),
'C': () => new C(),
};
...
var a = factories['A']();
您可以將工廠集成到班級中
class A {
static A createNew() => new A();
}
var factories = {
'A': A.createNew,
'B': B.createNew,
'C': C.createNew,
};
...
var a = factories['A']();
您是否可以使用自定義工廠生成響應,並將其傳遞給RPC類。 這對我來說非常簡單:
class RPC<REQ extends Message, RES extends Message> {
static MessageFactory factory;
RES submit(REQ req, String uri){
// ...
RES res = factory.createRES();
// ..
}
}
abstract class MessageFactory {
RES createRES();
}
class TestFactory extends MessageFactory {
RES createRES() {
return new TestResponse();
}
}
//代碼中的某個地方
RPC.factory = new TestFactory();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.