【问题标题】:Implement Iterator design pattern using JDBC使用 JDBC 实现迭代器设计模式
【发布时间】:2013-05-16 20:53:54
【问题描述】:

我正在解决以下问题:

迭代器设计模式是一种具有强封装性的模式。举个例子;图书馆需要图书管理系统。 books 存储其详细信息的类和 library 存储书籍和书架号的类。假设图书馆希望使用JDBC 将数据存储在数据库中。

如何使用 JDBC 实现迭代器设计模式以确保数据封装?

我关心的是在哪里处理数据库以及如何在应用程序之间共享数据。

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

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

【问题讨论】:

  • 迭代器用于遍历集合。这个问题是从哪里来的?
  • @TonyHopkinson - 实际上迭代器用于遍历任何事物,并且数据库查询结果非常非常适合迭代器。
  • @Waddas - 你在正确的轨道上,内部类实现Iterator<Something>,并使外部类实现Iterable。你认为Something 在这种情况下会是什么。
  • @OldCurmudgeon 我在想(按照示例)Map<Integer, Book>,整数是 UID。快速思考一下,将它作为内部类是不是非常低效?每次请求图书馆的数据时,都需要关闭当前数据库并打开一个新数据库。
  • @Waddas - 不 - 查看连接池。

标签: java database design-patterns jdbc iterator


【解决方案1】:

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

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.");
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 2020-08-13
    • 2020-09-09
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多