迭代器模式:提供一种可以遍历聚合对象的方式,又叫游标cursor模式
迭代器需要实现的功能
package com.dasenlin.baidu;
/**
* 自己定义的对象
* @author Administrator
*
*/
public interface MyIterator {
void first();
void next();
boolean hasNext();
boolean isFirst();
boolean isLast();
Object getCurrentObj();
}
迭代器的实现
package com.dasenlin.baidu;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义的聚合类
* @author Administrator
*
*/
public class ConcreateMyAggregate {
private List<Object> list = new ArrayList<Object>();
/* public ConcreateMyAggregate(List<Object> list) {
super();
this.list = list;
}*/
public void addObject(Object obj){
this.list.add(obj);
}
public void removeObject(Object obj){
this.list.remove(obj);
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public MyIterator createIterator(){
return new ConcreateIterator();
}
private class ConcreateIterator implements MyIterator{
private int cursor;
@Override
public void first() {
cursor=0;
}
@Override
public void next() {
if(cursor<list.size()){
cursor++;
}
}
@Override
public boolean hasNext() {
if(cursor<list.size()){
return true;
}
return false;
}
@Override
public boolean isFirst() {
return cursor==0?true:false;
}
@Override
public boolean isLast() {
return cursor==(list.size()-1)?true:false;
}
@Override
public Object getCurrentObj() {
return list.get(cursor);
}
}
}
测试客户端
package com.dasenlin.baidu;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
ConcreateMyAggregate cma = new ConcreateMyAggregate();
cma.addObject("aa");
cma.addObject("bb");
cma.addObject("cc");
MyIterator iter = cma.createIterator();
while(iter.hasNext()){
System.out.println(iter.getCurrentObj());
iter.next();
}
}
}