迭代器模式

定义:提供一种方法,顺序访问聚合对象中的各个元素,而又不暴露其内部的表示。

类图

迭代器模式

示例

public class Book {
    private String name;
    private String author;

    public Book(String name, String author) {
        this.name = name;
        this.author = name;
    }

    @Override
    public String toString() {
        return "[name:"+name+"\t author:"+author+"]";
    }
}

//iterator
public interface Iterator {
    boolean hasNext();
    Object next();
}

//ConcreteIterator
public class BookArrayIterator implements Iterator {
    Book[] books;
    int position = 0;
    public BookArrayIterator(Book[] books){
        this.books = books;
    }
    @Override
    public boolean hasNext() {
        if(position>=books.length){
            return false;
        }
        return true;
    }

    @Override
    public Object next() {
        return books[position++];
    }
}

//aggregate
public interface Items {
    Iterator createIterator();
}

//ConcreteAggregate
public class BookItems implements Items {
    Book[] books;
    public BookItems(Book[] books){
        this.books = books;
    }
    @Override
    public Iterator createIterator() {
        return new BookArrayIterator(books);
    }
}

public class Client {
    public static void main(String[] args) {
        //初始化书单
        Book book1 = new Book("book1", "author1");
        Book book2 = new Book("book2", "author2");
        Book book3 = new Book("book3", "author3");
        Book[] books = {book1, book2, book3};
        BookItems bookItems = new BookItems(books);
        //客户调用迭代器
        Iterator bookIterator = bookItems.createIterator();
        while (bookIterator.hasNext()) {
            System.out.println(bookIterator.next());
        }
    }
}

运行结果

迭代器模式

 

上一篇:Redis(1)——5种基本数据结构


下一篇:ZOJ4067 Books(思维)