Java分页类封装

在开发中,分页功能是常见的需求之一。为了提高代码的可复用性和可维护性,我们可以将分页逻辑封装到一个独立的类中。本文将介绍如何使用Java封装分页类,并提供代码示例。

分页类设计

分页类通常需要包含以下信息:

  • 当前页码(currentPage)
  • 每页显示的记录数(pageSize)
  • 总记录数(totalRecords)
  • 总页数(totalPages)

基于这些信息,我们可以设计一个分页类。以下是类图:

classDiagram
    class Page {
        <<abstract>>
        - currentPage int
        - pageSize int
        - totalRecords int
        - totalPages int
        + calculateTotalPages() int
    }
    class PageImpl {
        - records List
        + PageImpl(currentPage, pageSize, totalRecords)
        + getRecords() List
        + getCurrentPage() int
        + getPageSize() int
        + getTotalRecords() int
        + getTotalPages() int
    }

分页类实现

以下是分页类的实现代码:

public abstract class Page {
    protected int currentPage;
    protected int pageSize;
    protected int totalRecords;

    public Page(int currentPage, int pageSize, int totalRecords) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalRecords = totalRecords;
    }

    public abstract int calculateTotalPages();
}

public class PageImpl<T> extends Page {
    private List<T> records;

    public PageImpl(int currentPage, int pageSize, int totalRecords) {
        super(currentPage, pageSize, totalRecords);
    }

    public List<T> getRecords() {
        return records;
    }

    public void setRecords(List<T> records) {
        this.records = records;
    }

    @Override
    public int calculateTotalPages() {
        return (int) Math.ceil((double) totalRecords / pageSize);
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getTotalRecords() {
        return totalRecords;
    }

    public int getTotalPages() {
        return calculateTotalPages();
    }
}

使用分页类

以下是如何使用分页类的示例:

public class Main {
    public static void main(String[] args) {
        List<String> data = Arrays.asList("Record1", "Record2", "Record3", "Record4", "Record5", "Record6", "Record7", "Record8", "Record9", "Record10");

        PageImpl<String> page = new PageImpl<>(1, 5, data.size());
        page.setRecords(data.subList((page.getCurrentPage() - 1) * page.getPageSize(), page.getCurrentPage() * page.getPageSize()));

        System.out.println("Current Page: " + page.getCurrentPage());
        System.out.println("Page Size: " + page.getPageSize());
        System.out.println("Total Records: " + page.getTotalRecords());
        System.out.println("Total Pages: " + page.getTotalPages());
        System.out.println("Records: " + page.getRecords());
    }
}

结语

通过封装分页类,我们可以将分页逻辑与业务逻辑分离,提高代码的可复用性和可维护性。同时,分页类的设计也使得分页功能的扩展变得更加容易。希望本文能够帮助你更好地理解和实现Java分页功能。