迭代器模式(Iterator)
2017-08-16 本文已影响0人
bobcorbett
迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
主方法
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
ConcreteAggregate a = new ConcreteAggregate();
List<Object> items = new ArrayList<Object>();
items.add("大鸟");
items.add("小菜");
items.add("行李");
items.add("老外");
items.add("公交内部员工");
items.add("小偷");
a.setItems(items);
Iterator i = new ConcreteIterator(a);
while (!i.isDone()) {
System.out.println(String.format("{%s}请买车票!", i.currentItem()));
i.next();
}
}
}
抽象类
/**
* 迭代器抽象类
*/
public abstract class Iterator {
public abstract Object first();
public abstract Object next();
public abstract boolean isDone();
public abstract Object currentItem();
}
/**
* 聚集抽象类
*/
public abstract class Aggregate {
public abstract Iterator createIterator();
}
实现类
public class ConcreteIterator extends Iterator {
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate) {
this.aggregate = aggregate;
}
public Object first() {
return aggregate.getItems().get(0);
}
public Object next() {
Object ret = null;
current++;
if (current < aggregate.count()) {
ret = aggregate.getItems().get(current);
}
return ret;
}
public boolean isDone() {
return current >= aggregate.getItems().size() ? true : false;
}
public Object currentItem() {
return aggregate.getItems().get(current);
}
}
import java.util.ArrayList;
import java.util.List;
public class ConcreteAggregate extends Aggregate {
private List<Object> items = new ArrayList<Object>();
public Iterator createIterator() {
return new ConcreteIterator(this);
}
public int count() {
return items.size();
}
public List<Object> getItems() {
return items;
}
public void setItems(List<Object> items) {
this.items = items;
}
}