Iterator模式,
Iterator模式,
- Iterator模式角色
- Iterator(迭代器)
- ConcreteIterator(具体的迭代器)
- Aggregate(集合)
- ConcreteAggregate(具体的集合)
- 代码示例
- 类图接口
Iterator模式角色
我们在写Java代码的过程中,会经常用到集合类。在操作集合的过程中,会经常用到Iterator。下面介绍一下Iterator模式中的角色:
Iterator(迭代器)
该角色定义了按顺序逐个遍历元素的API,它定义了hasNext和next两个方法。(示例程序中的Iterator)
ConcreteIterator(具体的迭代器)
该角色负责实现Iterator所定义的API,包含了遍历集合所必须的信息。(示例程序中的BookShelfIterator)
Aggregate(集合)
该角色定义了创建Iterator角色的API。(示例程序中的Aggregate)
ConcreteAggregate(具体的集合)
该角色负责实现Aggregate角色所定义的API,它会创建出具体的Iterator角色。
代码示例
Aggregate:表示集合的接口
/**
* 表示集合的接口
*
* Created by xuefeihu on 18/4/11.
*/
public interface Aggregate {
Iterator iterator();
}
Iterator:遍历集合的接口
/**
* 遍历集合的接口
*
* Created by xuefeihu on 18/4/11.
*/
public interface Iterator {
boolean hasNext();
Object next();
}
Book:表示书的类
/**
* 表示书的类
*
* Created by xuefeihu on 18/4/11.
*/
public class Book {
private String name;
// getter and setter
}
BookShelf:表示书架的类
/**
* 表示书架的类
*
* Created by xuefeihu on 18/4/11.
*/
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 book) {
this.books[last] = book;
last++;
}
public int getLength() {
return last;
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
BookShelfIterator:遍历书架的类
/**
* 遍历书架的类
*
* Created by xuefeihu on 18/4/11.
*/
public class BookShelfIterator implements Iterator {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
} else {
return false;
}
}
public Object next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
Main:测试入口
/**
* 测试程序行为的类
*
* Created by xuefeihu on 18/4/11.
*/
public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(4);
bookShelf.appendBook(new Book("Around the world in 80 Days"));
bookShelf.appendBook(new Book("Bible"));
bookShelf.appendBook(new Book("Cinderella"));
bookShelf.appendBook(new Book("Daddy-Long-Legs"));
Iterator iterator = bookShelf.iterator();
while (iterator.hasNext()) {
Book book = (Book) iterator.next();
System.out.println(book.getName());
}
}
}
类图接口
参考:《图解设计模式》
链接:http://moguhu.com/article/detail?articleId=65
评论暂时关闭