Java Iterator模式

Iterator迭代器的定义:迭代器(Iterator)模式,又叫做游标(Cursor)模式。GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。

直接看代码分析理解:

接口Iterator集合迭代器

/**
 * @Acthor:
 * @ClassName:Iterator
 * @Description:循环遍历
 */
public interface Iterator {
    boolean hasNext();
    Object next();
}

接口Aggregate生成集合迭代器

/**
 * @Acthor:
 * @ClassName:Aggregate
 * @Description:该接口生成遍历集合的迭代器
 */
public interface Aggregate {
    Iterator iterator() ;
}

 遍历集合对象book

/**
 * @Acthor:
 * @ClassName:book
 * @Description:遍历对象是书
 */
public class book {
    private String name;
    public book(String name){
        this.name = name ;
    }

    public String getName() {
        return name;
    }
}

 创建放书的容器书柜BookShelf

/**
 * @Acthor:
 * @ClassName:BookShelf
 * @Description:书柜是放书的容器
 */
public class BookShelf implements Aggregate{
    private book[] books ;
    private int last = 0 ;
    public BookShelf(int maxSize){
        this.books = new book[maxSize];
    }

    public book getBookAt(int index) {
        return books[index];
    }
    public void appendBook(book books){
        this.books[last] = books ;
        last++ ;
    }
    public int getLength(){
        return last ;
    }
    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}

 遍历书柜(容器)中的书

/**
 * @Acthor:
 * @ClassName:
 * @Description:遍历书柜容器的书
 */
public class BookShelfIterator implements Iterator {
    private BookShelf bookShelf ;
    private int index ;
    public BookShelfIterator(BookShelf bookShelf){
        this.bookShelf = bookShelf ;
        this.index = 0 ;
    }
    @Override
    public boolean hasNext() {
        if(index <bookShelf.getLength()){
            return true ;
        }else {
            return false;
        }
    }

    @Override
    public Object next() {
        book b = bookShelf.getBookAt(index);
        index++ ;
        return b;
    }
}

测试代码

import java.awt.print.Book;

/**
 * @Acthor:
 * @ClassName:
 * @Description:
 */
public class MainDemo {
    public static void main(String[] args){
        BookShelf bookShelf =new BookShelf(4);
        bookShelf.appendBook(new book("A"));
        bookShelf.appendBook(new book("C"));
        bookShelf.appendBook(new book("B"));
        Iterator iterator = bookShelf.iterator() ;
        while(iterator.hasNext()){
            book b = (book) iterator.next();
            System.out.print(b.getName());
        }
    }
}

  以上就是迭代模式的一个小程序,可以看出要想使用迭代模式开发程序首先需要一个Iterator接口(迭代器),接口中定义你所需要的方法。然后定一个Aggregate接口是生成一个迭代器,该接口是实现

BookShelfIterator 书柜(容器)的遍历。再定义一个你所需要遍历的对象book类和需要存储book对象的BookShref书柜(容器)。
  
原文地址:https://www.cnblogs.com/x-ll123/p/7834589.html