重点等级::star::star::star::star::star:
迭代器模式提供了一种方法顺序访问一个聚合对象中的各个元素,而又无需暴露该对象的内部实现,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。
- 访问一个集合对象的内容而无需暴露它的内部表示
- 为遍历不同的集合结构提供一个统一的接口
定义几个角色:
- Iterator(抽象迭代器)。这里使用
java.util.Iterator
代替,也可以自己重新定义 - BookIterator(具体迭代器)
- Aggregate(抽象聚合类)。它用于存储和管理元素对象,充当抽象迭代器工厂角色。
- BookAggregateImpl(具体聚合类)
public class Book {
private String name;
public Book(){
}
public Book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
public class BookIterator implements Iterator<Book> {
private Aggregate<Book> bookAggregate;
private int index;
public BookIterator(Aggregate<Book> bookAggregate){
this.bookAggregate = bookAggregate;
index = 0;
}
@Override
public boolean hasNext() {
if (index < bookAggregate.length()) return true;
return false;
}
@Override
public Book next() {
return bookAggregate.get(index++);
}
}
public interface Aggregate<T> {
Iterator<T> iterator();
T get(int i);
void add (T t);
int length();
}
public class BookAggregateImpl implements Aggregate<Book> {
private Book[] books;
private int position;
public BookAggregateImpl(int max_length){
books = new Book[max_length];
position = 0;
}
@Override
public Iterator<Book> iterator() {
return new BookIterator(this);
}
@Override
public void add(Book t) {
books[position++] = t;
}
@Override
public Book get(int i) {
return books[i];
}
@Override
public int length(){
return position;
}
}
public static void main(String[] args) {
Book book1 = new Book("book1");
Book book2 = new Book("book2");
Book book3 = new Book("book3");
Book book4 = new Book("book4");
Book book5 = new Book("book5");
Aggregate aggregate = new BookAggregateImpl(5);
aggregate.add(book1);
aggregate.add(book2);
aggregate.add(book3);
aggregate.add(book4);
aggregate.add(book5);
Iterator<Book> it = aggregate.iterator();
while (it.hasNext()) {
Book book = it.next();
System.out.println(book.getName());
}
}
java.util.Iterator
java.util.Enumeration