迭代器模式:
又叫做游标(Cursor)模式。
提供一种方法访问一个容器(container)对象中的各个元素,而又不暴露该对象的内部细节。
/**
* Created by malei on 2016/12/6.
*/
public class MyList<T> implements Collect<T>{
private List list = new ArrayList();
@Override
public void add(T obj) {
list.add(obj);
}
@Override
public void remove(T obj) {
list.remove(obj);
}
@Override
public Iterator iterator() {
return new MyIterator(list);
}
public static void main(String[] args){
Collect<String> list = new MyList<>();
list.add("小米1");
list.add("小米2");
list.add("小米3");
Iterator it = list.iterator();
while (it.hasNext()){
Log.show((String)it.next());
}
}
}
/**
* Created by malei on 2016/12/6.
* 集合的接口规范
*/
public interface Collect<T> {
void add(T obj);
void remove(T obj);
Iterator iterator();
}
/**
* Created by malei on 2016/12/6.
*/
public class MyIterator<T> implements Iterator{
private List<T> list = new ArrayList();
private int cursor = 0;
public MyIterator(List<T> list){
this.list = list;
}
@Override
public T next() {
T obj = null;
if(this.hasNext()){
obj = this.list.get(cursor++);
}
return obj;
}
@Override
public boolean hasNext() {
if(cursor == list.size()){
return false;
}
return true;
}
}
/**
* Created by malei on 2016/12/6.
* 迭代器接口
*/
public interface Iterator <T>{
T next();
boolean hasNext();
}