图解设计模式(一)迭代器模式

本文深入讲解了迭代器模式的原理及应用,展示了如何通过迭代器模式遍历聚合类中的元素,包括创建BookShelf类和相应的迭代器实现,提供了一种灵活的遍历方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迭代器模式

在这里插入图片描述

import java.util.ArrayList;

/**
 * 迭代器模式:
 * 适用于需要对聚合类实现遍历的场景。每个新增一个聚合类,需新增对应的迭代器。
 * @author zhaozx
 * @create 2018-11-22 下午7:57
 */
public class IteratorPattern {
    public static void main(String[] args) {
        BookShelf<Book> bookShelf = new BookShelf<>(5);
        bookShelf.appendBook(new Book("Java"));
        bookShelf.appendBook(new Book("C"));
        bookShelf.appendBook(new Book("Python"));
        bookShelf.appendBook(new Book("PHP"));
        

        Iterator<Book> iterator = bookShelf.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

/**
 * 聚合类接口
 */
interface Aggregate<T> {
    Iterator<T> iterator();
}

/**
 * 迭代器接口
 * @param <T>
 */
interface Iterator<T> {
    boolean hasNext();
    T next();
}

class Book {
    private String name;
    public Book(String name) {this.name = name;}
    public String getName() {
        return name;
    }
    public String toString() {
        return new String("Book: " + name);
    }
}

/**
 * 集合类,包含对个对象,如Book,例子使用数组作为集合例子
 */
class BookShelf<T> implements Aggregate<T> {
    private ArrayList<T> book;
    private int last;
    public BookShelf (int maxSize) {
        book = new ArrayList<T>(maxSize);
    }
    public T getBookAt(int index) {
        return (T) book.get(index);
    }
    public void appendBook (T book) {
        this.book.add(last++, book);
    }
    public int getLength() {
        return last;
    }
    public Iterator<T> iterator() {
        return new BookShelfIterator<T>(this);
    }
}

/**
 * 迭代器实现,与聚合类BookShelf相对应。
 * 迭代器模式下,每一个聚合类应当有自己的迭代器实现类.
 * 迭代器类可以实现多种方式遍历聚合类,如顺序、倒序遍历
 */
class BookShelfIterator<T> implements Iterator {
    BookShelf<T> bookShelf;
    int cursor;
    public BookShelfIterator (BookShelf<T> bookShelf) {
        this.bookShelf = bookShelf;
    }

    @Override
    public boolean hasNext() {
        return cursor < bookShelf.getLength();
    }

    @Override
    public T next() {
        return (T)bookShelf.getBookAt(cursor++);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值