设计思路
角色分析
1.Iterator(迭代器):
该角色负责定义Iterator。hasNext方法用于判断是否存在下一个元素,next方法用于获取当前元素并指针下移。
2.ConcreteIterator(迭代器实现类):
该角色负责实现Iterator。
3.Aggregate(集合):
该角色负责定义调用的Iterator的种类。
4.ConcreteAggregate(集合的实现类):
该角色负责返回当前对象的Iterator。
UML图
代码演示
接口和类一览表
名字 | 说明 |
---|---|
Aggregate | 表示集合的接口 |
Iterator | 遍历集合的接口 |
Book | 表示书的类 |
BookShelf | 表示书架的类 |
BookShelfIterator | 遍历书架的类 |
Main | 程序的入口类 |
代码
迭代器接口
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
集合接口
public interface Aggregate {
public abstract Iterator iterator();
}
书籍实体类
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
'}';
}
}
书架实体类
import java.util.ArrayList;
import java.util.List;
public class BookShelf implements Aggregate {
private List<Book> books;
private int length;
public BookShelf() {
books = new ArrayList<>();
length = 0;
}
public Book getBookAt(int index) {
return books.get(index);
}
public void appendBook(Book book) {
books.add(book);
length++;
}
public int getLength() {
return length;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
书架迭代器
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 book = bookShelf.getBookAt(index);
index++;
return book;
}
}
主类
public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf();
bookShelf.appendBook(new Book("环游世界80天"));
bookShelf.appendBook(new Book("圣经"));
bookShelf.appendBook(new Book("灰姑娘"));
bookShelf.appendBook(new Book("长腿爸爸"));
Iterator iterator = bookShelf.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}