迭代器模式
目前是一个已经没落的模式,基本上没人会单独写一个迭代器模式。
它提供一种方法访
//抽象迭代器
public interface Iterator {
public Object next();
public boolean hasNext();
public boolean remove();
}
//具体迭代器
public class ConcreteIterator implements Iterator {
private Vector<Object> vector = new Vector<Object>();
private int cursor = 0 ;
public ConcreteIterator(Vector<Object> vector) {
super();
this.vector = vector;
}
@Override
public Object next() {
Object result = null;
if (this.hasNext()) {
result=this.vector.get(cursor++);
}else{
result = null;
}
return result;
}
@Override
public boolean hasNext() {
if (this.cursor == vector.size() ) {
return false;
} else {
return true;
}
}
@Override
public boolean remove() {
this.vector.remove(this.cursor);
return true;
}
}
//抽象容器
public interface Aggregate {
public void add(Object ob);
public void remove(Object ob);
public Iterator iterator();
}
//具体容器
public class ConcreteAggregate implements Aggregate {
private Vector<Object> vector = new Vector<>();
@Override
public void add(Object ob) {
this.vector.add(ob);
}
@Override
public void remove(Object ob) {
this.vector.remove(ob);
}
@Override
public Iterator iterator() {
return new ConcreteIterator(this.vector);
}
}
public class Client {
public static void main(String[] args) {
Aggregate aggregate =new ConcreteAggregate();
aggregate.add("abc");
aggregate.add("bca");
aggregate.add("er");
Iterator iterator = aggregate.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
问一个容器对象中的各个元素,而又不需要暴露该对象的内部细节。