Iterator(迭代器接口):
ConcreteIterator(迭代器实现类):
Aggregate(容器接口):
ConcreteAggregate(容器实现类):
public interface IDieDai<T> {
Boolean hasNext();
T next();
}
public class DieDai<T> implements IDieDai<T> {
ArrayList<T> list = new ArrayList<>();
public DieDai(ArrayList<T> list) {
this.list = list;
}
int size = 0;
@Override
public Boolean hasNext() {
return size != list.size();
}
@Override
public T next() {
T value = null;
if (hasNext() == true) {
value = this.list.get(size++);
}
return value;
}
}
public interface IContainer<T> {
void add(T t);
void remove(T t);
IDieDai dieDai();
}
public class Container<T> implements IContainer<T> {
ArrayList<T> list = new ArrayList<>();
@Override
public void add(T o) {
list.add(o);
}
@Override
public void remove(T o) {
list.add(o);
}
@Override
public IDieDai dieDai() {
return new DieDai(this.list);
}
}
测试
public class Test {
public static void main(String[] args) {
Container<String> stringContainer = new Container<>();
stringContainer.add("hello");
stringContainer.add("world");
IDieDai iDieDai = stringContainer.dieDai();
while (iDieDai.hasNext()){
System.out.println(iDieDai.next());
}
}
}
网友评论