定義:迭代器模式提供一種不暴露集合就能訪問集合內多態對象的途徑
使用場景:需要遍歷某個集合時
類圖:

代碼樣例:
package headfirst.iterator.dinermerger;
public class MenuItem {
String name;
String description;
boolean vegetarian;
double price;
public MenuItem(String name,
String description,
boolean vegetarian,
double price)
{
this.name = name;
this.description = description;
this.vegetarian = vegetarian;
this.price = price;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public boolean isVegetarian() {
return vegetarian;
}
public String toString() {
return (name + ", $" + price + "\n " + description);
}
}
package headfirst.iterator.dinermerger;
public interface Iterator {
boolean hasNext();
Object next();
}
package headfirst.iterator.dinermerger;
public class ArrayIterator implements Iterator {
MenuItem[] items;
int position = 0;
public ArrayIterator(MenuItem[] items) {
this.items = items;
}
public Object next() {
MenuItem menuItem = items[position];
position = position + 1;
return menuItem;
}
public boolean hasNext() {
if (position >= items.length || items[position] == null) {
return false;
} else {
return true;
}
}
}
優點:1)提供一種訪問集合元素的統一方法,使用者不需要關注該集合的底層實現 2)將遍歷集合和管理集合分離,使集合本身僅關注於管理
缺點:
類似的設計模式:
配套的內功心法:1)一個類應該只有一個改變的理由 2)凝聚性用來度量一個類或者模塊僅關注一個功能的程度,一個類如果僅包含一組非常相近的功能,我們稱這個類具有高凝聚性。