泛型相关请参考:http://www.cnblogs.com/lwbqqyumidi/p/3837629.html
uml:
Aggregate及其子类:
public abstract class Aggregate<T> { public abstract Iterator<T> getIterator(); public abstract T get(int index); public abstract int getLength(); public abstract void add(T e); public abstract void remove(T e); } import java.util.ArrayList; import java.util.List; public class ConcreteAggregate<T> extends Aggregate<T> { private List<T> list = new ArrayList<>(); @Override public int getLength(){ return list.size(); } @Override public void add(T item) { list.add(item); } @Override public void remove(T item) { list.remove(item); } @Override public T get(int index){ return list.get(index); } @Override public Iterator<T> getIterator() { return new ConcreteIterator<T>(this); } }
Iterator及其子类:
public abstract class Iterator<T> { public abstract boolean hasNext(); public abstract T next(); } public class ConcreteIterator<T> extends Iterator<T> { private ConcreteAggregate<T> aggr; private int current = 0; public ConcreteIterator(ConcreteAggregate<T> aggr) { this.aggr = aggr; } @Override public boolean hasNext() { return current < aggr.getLength() ? true : false; } @Override public T next() { // TODO Auto-generated method stub current++; return aggr.get(current - 1); } }
Demo:
public class IteratorDemo { public static void main(String[] args) { Aggregate<Integer> aggregate = new ConcreteAggregate<>(); for(int i = 0; i < 10; i++){ aggregate.add(i); } Iterator<Integer> iterator = aggregate.getIterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }