迭代器UML.png迭代器模式
public interface Iterator<T>{
boolean hasNext();
T next();
}
迭代器接口
public class ConcreteIterator<T> implements Iterator<T> {
private List<T> list = new ArrayList<T>();
private int cursor = 0;
public ConcreteIterator(List<T> list){
this.list = list;
}
public boolean hasNext(){
return cursor != list.size();
}
public T next(){
T obj = null;
if(this.next()){
obj = this.list.get(cursor++);
}
return obj;
}
}
具体迭代器类
public interface Aggregate<T>{
void add(T obj);
void remove(T obj);
Iterator<T> iterator();
}
容器接口
public class ConcreteAggregate<T> implements Aggregate<T>{
private List<T> list = new ArrayList<>();
public void add(T obj){
list.add(obj);
}
public void remove(T obj){
list.remove(obj);
}
public Iterator<T> iterator(){
return new ConcreteIterator<T>(list);
}
}
具体容器类
public class Client{
public static void main(String args[]){
Aggregate<String> data = new ConcreteAggregate<>();
data.add("1");
data.add("2");
data.add("3");
data.add("4");
Iterator<String> i = data.iterator();
whihe(i.hasNext()){
System.out.print(i.next());
}
}
}
客户端
个人理解
在java中的集合是迭代器模式的最好体现。在Android中数据库查询所用到的Cursor,用query方法查询数据库会返回一个Cursor游标,用它来遍历数据。
网友评论