定义
提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。
迭代器模式通用类图
角色
Iterator(迭代器)
该角色负责定义按顺序逐个遍历元素的接口。
ConcreteIterator(具体的迭代器)
该角色负责实现 Iterator 角色所定义的接口。
Aggregate(集合)
该角色负责定义创建 Iterator 角色的接口。
ConcreteAggregate(具体的集合)
该角色负责实现 Aggregate 角色所定义的接口。
迭代器模式,将遍历与实现分离开来。
实现
/**
*定义 迭代器 接口
*/
public interface Iterator<T> {
boolean hasNext();
T next();
}
/**
*定义 聚合 接口
*/
public interface Aggregate<T> {
Iterator<T> iterator();
}
/**
* 具体的集合
*/
public class BookShel<T> implements Aggregate<T> {
private Object[] objects;
private int last = 0;
public BookShelf(int maxsize) {
this.objects = new Object[maxsize];
}
@SuppressWarnings("unchecked")
public T getAt(int index) {
return (T)objects[index];
}
public void append(T t) {
this.objects[last] = t;
last++;
}
public int getLength() {
return last;
}
@Override
public Iterator<T> iterator() {
return new BookShelfIterator<T>(this);
}
}
/**
* 具体的迭代器
*/
public class BookShelfIterator<T> implements Iterator<T>{
private BookShelf<T> bookShelf;
private int index;
public BookShelfIterator(BookShelf<T> bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
}
return false;
}
@Override
public T next() {
T obj = bookShelf.getAt(index);
index++;
return obj ;
}
}
/**
* 实体类
*/
public class Book {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Book(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book [name=" + name + "]";
}
}
/**
* main方法
*/
public class IteratorMain {
public static void main(String[] args) {
BookShelf<Book> bookShelf = new BookShelf<Book>(10);
Book book = new Book("九阴真经");
bookShelf.append(book);
Book book1 = new Book("天龙八部");
bookShelf.append(book1);
Iterator<Book> iterators = bookShelf.iterator();
while (iterators.hasNext()) {
Book nextBook = iterators.next();
System.out.println(nextBook);
}
}
}