迭代器模式提供一種方法順序訪問一個聚合對象中各個元素,而又不需暴露該對象的內部表示,屬於行爲模式的一種 bash
優勢:ide
缺點:ui
因爲迭代器模式將存儲數據和遍歷數據的職責分離,增長新的聚合類須要對應增長新的迭代器類,類的個數成對增長,這在必定程度上增長了系統的複雜性spa
定義抽象迭代器Iteratorcode
public interface Iterator<T> {
boolean hasNext();
T first();
T next();
}
複製代碼
定義具體迭代器FilmMenuIteratorcdn
public class FilmMenuIterator implements Iterator<MenuItem> {
private List<MenuItem> menuItems;
private int position = 0;
public FilmMenuIterator(List<MenuItem> itemList) {
menuItems = itemList;
}
@Override
public boolean hasNext() {
if (position > menuItems.size() - 1 || menuItems.get(position) == null) {
return false;
} else {
return true;
}
}
@Override
public MenuItem first() {
return menuItems.size() > 0 ? menuItems.get(0) : null;
}
@Override
public MenuItem next() {
MenuItem menuItem = menuItems.get(position);
position++;
return menuItem;
}
}
複製代碼
定義抽象容器MenuAggregate對象
public interface MenuAggregate<T> {
void addItem(int id, String name);
Iterator<T> create();
}
複製代碼
定義具體容器FilmAggregateblog
public class FilmAggregate implements MenuAggregate<MenuItem> {
private List<MenuItem> menuItems;
public FilmAggregate() {
menuItems = new ArrayList<>();
}
@Override
public void addItem(int id, String name) {
menuItems.add(new MenuItem(id, name));
}
@Override
public Iterator<MenuItem> create() {
return new FilmMenuIterator(menuItems);
}
}
複製代碼
客戶端實現接口
FilmAggregate film = new FilmAggregate();
film.addItem(1, "西紅柿首富");
film.addItem(2, "兄弟");
film.addItem(2, "反貪風暴");
Iterator it = film.create();
while(it.hasNext()){
System.out.println(it.next().toString());
}
複製代碼