迭代器模式
Posted 不停的奋斗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了迭代器模式相关的知识,希望对你有一定的参考价值。
集合类中包含很多数据结构:数组、散列表、ArrayList等,这些集合类的迭代方法都不一样。为了隐藏迭代的具体实现 ,抽象集合类中引用抽象迭代器,具体的集合类引用具体的迭代类,在具体迭代类实现便利具体集合类的方法
package iterator;
import java.util.Iterator;
/**
* 抽象集合类,引用抽象迭代类
*/
public interface Aggregate {
public abstract Iterator createIterator();
}
package iterator;
import java.util.Iterator;
/**
* 具体集合类
*/
public class ArrayShelf implements Aggregate {
Book[] books;
int index = 0;
public ArrayShelf(int maxium) {
books = new Book[maxium];
}
public Book getBookAt(int index) {
return books[index];
}
public void appendBook(Book newBook) {
books[index++] = newBook;
}
public int getLength() {
return index;
}
@Override
public Iterator createIterator() {
return new ArrayIterator(this);
}
}
package iterator;
import java.util.Iterator;
/**
* 具体迭代类,Iterator是抽象迭代类
*/
public class ArrayIterator implements Iterator {
private ArrayShelf bookShelf;
private int index = 0;
public ArrayIterator(ArrayShelf bookShelf) {
this.bookShelf = bookShelf;
index = 0;
}
@Override
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
Book book = bookShelf.getBookAt(index++);
return book;
}
}
package iterator;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Created by marcopan on 17/4/7.
*/
public class ListIterator implements Iterator {
ListShelf arrays = new ListShelf();
int index = 0;
public ListIterator(ListShelf arrays) {
this.arrays = arrays;
index = 0;
}
@Override
public boolean hasNext() {
return (index < arrays.getLength());
}
@Override
public Object next() {
return arrays.getBook(index++);
}
}
package iterator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class ListShelf implements Aggregate {
List<Book> shelfList = new ArrayList<Book>();
public ListShelf() {
shelfList = new ArrayList();
}
public void append(Book book) {
shelfList.add(book);
}
public Book getBook(int index) {
return shelfList.get(index);
}
public int getLength() {
return shelfList.size();
}
@Override
public Iterator createIterator() {
return new ListIterator(this);
}
}
package iterator;
import java.util.Iterator;
/**
* Created by marcopan on 17/4/7.
*/
public class IteratorTest {
public static void main(String[] args) {
ArrayShelf shelf = new ArrayShelf(4);
shelf.appendBook(new Book("a"));
shelf.appendBook(new Book("b"));
shelf.appendBook(new Book("c"));
shelf.appendBook(new Book("d"));
/*ListShelf list = new ListShelf();
list.append(new Book("a"));
list.append(new Book("b"));
list.append(new Book("c"));
list.append(new Book("d"));*/
Iterator it = shelf.createIterator();
while (it.hasNext()) {
Book book = (Book)it.next();
System.out.println(book.getName());
}
}
}
以上是关于迭代器模式的主要内容,如果未能解决你的问题,请参考以下文章