迭代器模式几乎可以说是最常用的设计模式了,这种模式我们随处可见,用于顺序的访问对象的元素而不需要底层实现。迭代器模式属于行为性模式的一种,这类设计模式特别关注对象之间的通信。
常见的Iterator就是迭代器模式的一种,迭代器模式将存储数据和遍历数据的职责分离,但新增聚合类就需要增加对应的迭代器,在一定程度上增加了系统的复杂性。
类图:
具体代码实现:
public interface Aggregate {
Iterator iterator();
}
public interface Iterator {
public boolean hasNext();
public Object next();
}
public class Milk {
private String name;
public Milk(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MilkList implements Aggregate {
List<Milk> milks;
public MilkList() {
this.milks = new ArrayList<Milk>();
}
public Milk getMilk(int index) {
return milks.get(index);
}
public void appendMilk(Milk milk) {
milks.add(milk);
}
public int getLen() {
return milks.size();
}
public Iterator iterator() {
return new MilkListIterator(this);
}
}
public class MilkListIterator implements Iterator {
private int index;
private MilkList milkList;
public MilkListIterator(MilkList milkList) {
this.milkList = milkList;
this.index = 0;
}
public boolean hasNext() {
if(index < milkList.getLen()) {
return true;
} else {
return false;
}
}
public Object next() {
Milk milk = milkList.getMilk(index);
index ++;
return milk;
}
}
public class Client {
public static void main(String[] args) {
MilkList milkList = new MilkList();
milkList.appendMilk(new Milk("牛奶1号"));
milkList.appendMilk(new Milk("牛奶2号"));
milkList.appendMilk(new Milk("牛奶3号"));
Iterator iterator = milkList.iterator();
while(iterator.hasNext()) {
Milk milk = (Milk) iterator.next();
System.out.println(milk.getName());
}
}
}
/*
牛奶1号
牛奶2号
牛奶3号
*/
迭代器模式就介绍到这里啦,希望对你有所帮助!
愿每个人都能带着怀疑的态度去阅读文章并探究其中原理。
道阻且长,往事作序,来日为章。
期待我们下一次相遇!