大部分程序中都会需要分页算法,很明显,必须把分页算法独立出来,如果也业务逻辑夹杂在一起,修改起来,是一件痛苦的事情。其实分页算法的设计就像是解方程,输入几个变量,求出其他几个变量。下面给出一种简单的设计:输入总记录数,当前的页面,跳转页数;输出请求的索引。当然,你还可以在这个简单算法基础上修改,输出其他的一些信息。
package paging;
public class Page {
/**
* 每页显示的记录数,也就是你的请求数
*/
public static final int PAGESIZE = 20;
/**
* 总记录数
*/
private int records;
/**
* 当前页,从1开始计数
*/
private int now_page;
/**
* 总页数
*/
public int pages;
/**
* 请求位置,就是你从第几条记录开始请求
*/
public int request_index;
/**
* 是否成功构造Page对象
*/
public boolean ok = true;
public Page() {
}
/**
*一般在第一次请求的时候使用,因为不知道总记录数
*/
public Page(int now_page) {
this(PAGESIZE, now_page, 0);
}
public Page(int now_page, int go_count) {
this(PAGESIZE, now_page, go_count);
}
/**
*
* @param records
* 总记录书
* @param now_page
* 当前页面的索引
* @param go_count
* 跳转几页(支持负数)
*/
public Page(int records, int now_page, int go_count) {
if ((now_page - 1) * PAGESIZE >= records || now_page <= 0) {
System.out.println("构造Page失败-1!");
ok = false;
}
if (now_page + go_count <= 0 || (now_page + go_count - 1) * PAGESIZE >= records) {
System.out.println("构造Page失败-2!");
ok = false;
}
this.now_page = now_page;
this.records = records;
this.request_index = (this.now_page + go_count - 1) * PAGESIZE;
if (this.records % PAGESIZE == 0) {
this.pages = this.records / PAGESIZE;
} else {
this.pages = this.records / PAGESIZE + 1;
}
}
@Override
public String toString() {
return "pages:" + pages + " " + "request_index:" + request_index;
}
}
414

被折叠的 条评论
为什么被折叠?



