Iterator模式
Iterator英文意思是重复做某件事,中文翻译为迭代器,这个设计模式中主要有Iterator(迭代器),ConcreteIterator(具体的迭代器),Aggergate(集合),ConcreteAggregate(具体的集合)四个角色;下面举一个例子来说明。
对某个书架上的书进行遍历,并把每本书的书名打印到控制台上。
1,首先创建Aggergate和Iterator接口
public interface Aggregate { public abstract Iterator iterator(); }
public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); }
对于每个实现Aggergate的实现类,都会有一个方法生成自己的迭代器,每个迭代器都会有hasNext和next方法。
2,创建ConcreteIterator和ConcrereAggregate的类
public class Books { private String name; public Books(String name) { this.name = name; } public String getName() { return this.name; } }
import java.util.ArrayList; public class BookShelf implements Aggregate { private ArrayList books; public BookShelf(int initial) { this.books = new ArrayList(initial); } @Override public Iterator iterator() { return new BookShelfIterator(this); } public void appendBooks(Books books) { this.books.add(books); } public Books getBookAt(int index) { return (Books) books.get(index); } public int getLength() { return books.size(); } }
1 public class BookShelfIterator implements Iterator { 2 private BookShelf bookshelf; 3 4 private int index; 5 6 public BookShelfIterator(BookShelf bookShelf) { 7 this.bookshelf = bookShelf; 8 this.index = 0; 9 } 10 11 @Override 12 public boolean hasNext() { 13 if (index < bookshelf.getLength()) { 14 return true; 15 } else 16 return false; 17 } 18 19 @Override 20 public Object next() { 21 Books book = bookshelf.getBookAt(index); 22 index++; 23 return book; 24 } 25 26 }
具体的迭代器使用具体的集合的一个变量作为自己的字段,通过构造函数为具体的集合赋值,具体的集合通过Iterator生成迭代器
3,程序入口
1 public class Main { 2 3 public static void main(String[] args) { 4 BookShelf bookshelf = new BookShelf(4); 5 bookshelf.appendBooks(new Books("A")); 6 bookshelf.appendBooks(new Books("B")); 7 bookshelf.appendBooks(new Books("C")); 8 bookshelf.appendBooks(new Books("D")); 9 bookshelf.appendBooks(new Books("E")); 10 bookshelf.appendBooks(new Books("F")); 11 bookshelf.appendBooks(new Books("G")); 12 bookshelf.appendBooks(new Books("H")); 13 Iterator it = bookshelf.iterator(); 14 while (it.hasNext()) { 15 Books book = (Books) it.next(); 16 System.out.println(book.getName()); 17 } 18 } 19 20 }
Iterator设计模式体现了高聚合低耦合的设计思想,相比传统的循环代码,如果具体的集合中字段的储存方式发生了改变,仅需要对具体的集合那个类进行修改,而具体的迭代器和Main不用修改,一般的循环代码无法做到这一点。