大部分程式中都會需要分頁演算法,很明顯,必須把分頁演算法獨立出來,如果也商務邏輯夾雜在一起,修改起來,是一件痛苦的事情。其實分頁演算法的設計就像是解方程,輸入幾個變數,求出其他幾個變數。下面給出一種簡單的設計:輸入總記錄數,當前的頁面,跳轉頁數;輸出請求的索引。當然,你還可以在這個簡單演算法基礎上修改,輸出其他的一些資訊。
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;}}@Overridepublic String toString() {return "pages:" + pages + " " + "request_index:" + request_index;}}