假设我有一个类Point和一个函数来处理Point实例
类点 { 私有最终 int x, y; ... }
...
void handlePoints(Iterable<Point> points) { for (Point p: points) {...} }
现在我想points从文件中读取。文件的每一行都包含两个数字,所以我有一个函数(“工厂方法”)来point从一行创建一个。
点 makePoint(String line) { ... }
我现在该怎么办?我可以编写一个函数来将文件读取到列表中points并调用该handlePoints函数。
List<Point> readPoints(BufferedReader reader) {...} // 在这里使用 makePoint
无效句柄点(BufferedReader 阅读器){
List<Point> points = readPoints(reader);
处理点(点);
}
不幸的是,这个函数看起来并不是特别优雅,因为它在内存中创建了一个不必要的点列表。
使用迭代器不是更好吗?
void handlePoints(Iterator<Point> points) {...}
Iterator<Point> readPoints(BufferedReader reader) {...} // 这里使用 makePoint
无效句柄点(BufferedReader 阅读器){
迭代器<Point> 点 = readPoints(reader);
处理点(点);
}
是否有意义?这段代码在 Java 中不会太“嘈杂”吗?