场景:
- 提供一种可以遍历聚合对象的方式。又称为:游标cursor模式
- 聚合对象:存储数据
- 迭代器:遍历数据
基本案例
开发中常见的场景
一种实现
package com.coderbean.iterator;
/**
* Created by Chang on 15/10/3.
*/
public interface MyIterator {
void first();
void next();
boolean hasNext();
boolean isFirst();
boolean isLast();
Object getCurrentObj();
}
package com.coderbean.iterator;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义的聚合类
* Created by Chang on 15/10/3.
*/
public class ConcreteMyAggregate {
private List<Object> list = new ArrayList<Object>();
public void addObject(Object object){
this.list.add(object);
}
public void removeObject(Object object){
this.list.remove(object);
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public MyIterator createIterator(){
return new ConcreteIterator();
}
private class ConcreteIterator implements MyIterator {
private int cursor;
@Override
public void first() {
cursor = 0;
}
TE
@Override
public void next() {
if(this.hasNext()){
cursor++;
}
}
@Override
public boolean hasNext() {
if(cursor<list.size())
return true;
return false;
}
@Override
public boolean isFirst() {
return cursor==0;
}
@Override
public boolean isLast() {
return cursor==list.size()-1;
}
@Override
public Object getCurrentObj() {
return list.get(cursor);
}
}
}
package com.coderbean.iterator;
/**
* Created by Chang on 15/10/3.
*/
public class Client {
public static void main(String[] args) {
ConcreteMyAggregate concreteMyAggregate = new ConcreteMyAggregate();
concreteMyAggregate.addObject("aa");
concreteMyAggregate.addObject("bb");
concreteMyAggregate.addObject("cc");
MyIterator iter = concreteMyAggregate.createIterator();
while(iter.hasNext()){
System.out.println(iter.getCurrentObj());
iter.next();
}
}
}