java - 使用 JDBC 实现迭代器设计模式

标签 java database design-patterns jdbc iterator

我正在解决以下问题:

The iterator design pattern is one that has strong encapsulation. As an example; a library wants a book management system. A class for the books storing their details and a class for the library storing the books and the shelf number. Lets say the library wants the data stored in a database using JDBC.

How can the Iterator design pattern be implemented using JDBC ensuring encapsulation of the data?

My concern is where the database is being handled and how the data is being shared across the application.

数据库处理程序可以是库类的内部类吗?是否可以在不影响封装的情况下保存数据并根据请求检索数据?

我还在学习,还有很长的路要走,所以要温柔:)

最佳答案

这是一个关于使用迭代器模式访问数据库的近似。

package tk.ezequielantunez.stackoverflow.examples;

import java.util.Collection;
import java.util.Iterator;

/**
 * Paged implementatios of a DAO. Iterator interface is used.
 * Nottice you get pages of Collections, where resides your data.
 * @author Ezequiel
 */
public class DAOIterator implements Iterator<Collection> {

    int actualPage;
    int pageSize;

    public DAOIterator(int pageSize) {
        this.actualPage = 0;
        this.pageSize = pageSize;
    }

    /**
     * Indicates if you have more pages of datga.
     */
    @Override
    public boolean hasNext() {
        return actualPage < getTotalPages();
    }

    /**
     * Gets the next page of data.
     */
    @Override
    public Collection next() {
        return getPage(++actualPage);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Calculates total number of pages.
     */
    private int getTotalPages() {
        /* You could do a count of total results and divide them by pageSize */
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Get a page of results with X objects, where X is the pageSize used in
     * constructor.
     */
    private Collection getPage(int page) {
        /* Get data from database here */
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

关于java - 使用 JDBC 实现迭代器设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16597279/

相关文章:

php - PDO 的 LastInsertId 实际上是如何工作的?

asp.net - 分析 SQL Server 和/或 ASP.NET

python - 多个 Django 数据库 - 在同一应用程序中将模型映射到数据库

java - 单例客户端应该如何使用单例?

java - onResume 从堆栈中弹出 Activity

java - 在定义到方法中的类上使用 Gson 返回 null

java - 从发送到 AWS/Amazon SQS 的消息中删除无效字符

java - Swagger/Openapi-注释 : How to produce allOf with $ref?

c++ - C++ 中的变量全局常量 "macros"和最佳设计模式

c# - 有限状态机和封闭