我想创建一个处理Sockets的类层次结构。我有两个类,为了泛化,我们将它们命名为A和B。A是B扩展的超类。
下面是一个使用dart:io的示例
// a.dart
import "dart:async";
import "dart:io";
class A {
Future<String> socketStuff(String cmd) {
Completer com = new Completer();
Socket.connect("localhost", 5555).then((socket) {
socket.write(cmd);
socket.listen((data) {
String dataStr = new String.fromCharCodes(data);
com.complete(dataStr);
});
});
return com.future;
}
}//b.dart
import "a.dart";
class B extends A {
Future<String> doStuff() {
// Calls a method that does stuff with sockets, but doesn't really know
// it.
return socketStuff("doStuff");
}
Future<String> moreStuff() {
// Another method like the above one.
return socketStuff("moreStuff");
}
}问题是,我希望能够在命令行应用程序和web应用程序中使用它。类A要求我使用dart:io库或dart:http库。
我想出了几种方法来解决这个问题,但它可以增加相当多的复杂性。希望这会很清楚..。
I的接口。有A和一个新的类,A2,实现I。A将用于命令行应用程序,A2将用于web应用程序。问题是,创建类B的对象稍微复杂一些,因为B必须在其构造函数中使用A或A2。I的接口。有一个抽象类A,它包含所有共享方法的列表,并实现I,而不实际实现任何东西。然后有两个名为B和B2的类(一个用于命令行,另一个用于web),扩展A并实现I中缺少的方法。这个选项在很大程度上逆转了我已经拥有的功能,并引入了一个接口。我认为第二个选择是更好的选择,但是否还有其他人有其他想法来做这件事呢?
发布于 2014-01-20 12:27:09
如果我正确理解,我实际上会建议第三个解决方案(其他解决方案是可能的)。听起来您的B类将是一个帮助类,它将管理所有的逻辑,因此它应该包含一个"I“成员,它可以用io中的A1和控制台上的A2实例化。
下面是一个具体的示例,其中A是一个简单的HttpFetcher接口,用于从url获取字符串
// ihttp.dart
library ihttp;
import 'dart:async';
abstract class IHttpFetcher {
Future<String> getString(String uri);
}浏览器实现
// http_browser.dart
library http_browser;
import 'dart:html';
import 'dart:async';
import 'ihttp.dart';
class HttpBrowser implements IHttpFetcher {
@override
Future<String> getString(String uri) {
return HttpRequest.getString(uri);
}
}控制台实现(不确定这里是否正确处理错误)
// browser_console.dart
library http_console;
import 'dart:io';
import 'dart:async';
import 'ihttp.dart';
class HttpConsole implements IHttpFetcher {
HttpClient client = new HttpClient();
@override
Future<String> getString(String uri) {
var completer = new Completer<String>();
client.getUrl(Uri.parse(uri))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
StringBuffer body = new StringBuffer();
response.listen(
(data) => body.write(new String.fromCharCodes(data)),
onDone: () => completer.complete(body.toString()),
onError: (e) => completer.completeError(e));
})
.catchError((e) {
completer.completeError(e);
});
return completer.future;
}
}您的提供者的"B“类不依赖io或浏览器(也不能同时依赖于两者)和提供者助手函数。
// B.dart
library B;
import 'dart:async';
import 'ihttp.dart';
class B {
IHttpFetcher fetcher;
B(this.fetcher);
Future<String> getGoogleCom() => fetcher.getString("http://www.google.com");
Future<String> getHtml5Rocks() => fetcher.getString("http://updates.html5rocks.com");
}您将在控制台应用程序的主程序中负责根据需要实例化B。
// console version
import 'http_console.dart';
import 'B.dart';
B b = new B(new HttpConsole());或
// Browser version
import 'http_browser.dart';
import 'B.dart';
B b = new B(new HttpBrowser());在您共享的源代码中,您可以调用B助手
b.getGoogleCom().then((String content) {
print(content);
});祝好运!
https://stackoverflow.com/questions/21213550
复制相似问题