java:分页结果的设计模式
所以就有了Iterable
、Iterator
和List
。如果您尝试向其他 Java 代码提供接口,以便封装在“页面”中返回结果的远程服务提供的功能,您会使用什么?
作为示例,考虑数据库或网页(例如 flickr API)。第一次检索结果后,您知道结果总数和前 N 个结果,但在检索其余结果之前,您不知道其余结果。
So there's Iterable
and Iterator
and List
. What do you use if you are trying to provide an interface to other Java code, in order to encapsulate functionality provided by a remote service that returns results in "pages"?
As an example, consider a database or a webpage (e.g. flickr API). After the first retrieval of results, you know the total # of results and the first N results, but you don't know the remaining results until you retrieve the rest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的情况下,考虑到检索每个元素的成本很高,因此采用聚合结果而不是在删除调用级别直接迭代每个元素可能是有意义的。
您可以提供一个返回列表的方法,如下所示:
其中 offset 是您想要开始的第一个元素的索引, maxresults 是您想要在列表中包含的最大元素数。然后,您可以迭代要在页面中显示的列表。
Java Persistence API 也遵循相同的模式,Query 接口提供了 3 个方法来执行上述操作:
http://download.oracle.com/javaee/5/api/javax/persistence/Query.html
In your case, given that each element is expensive to retrieve, it probably makes sense to take aggregate results and not iterate directly for each element at remove invocation level.
You could provide one method which returns a List like this:
where offset would be the index of the first element you want to start from and maxresults is the maximum number of elements you want to have in the list. You can then iterate on the list to display in your page.
The Java Persistence API also follows the same pattern, the Query interface provides 3 methods that do the above:
http://download.oracle.com/javaee/5/api/javax/persistence/Query.html
我会保持与 Iterator 接口兼容,并且不会引入新方法(如上所述)。相反,我会在
hasElements()
中使用 延迟加载,nextElement()
和你的类 getter。I would stay compliant with
Iterator
interface, and wouldn't introduce new methods (as suggested above). Instead I would use lazy loading inhasElements()
,nextElement()
, and your class getters.在我的应用程序中,我决定实现
Iterator
,其中迭代器的next()
实现是下载下一页结果,而ListPage
code> 具有返回真实列表和元数据的方法,例如结果总数、每页数、页数和总页数:In my application I decided to implement
Iterator<ListPage>
, where the iterator's implementation ofnext()
is to download the next page of results, andListPage
has methods that return the real List and the metadata like total # of results, # per page, page #, and total # of pages: