来源:http://www.bjsxt.com/
一、S03E244_01【GOF23设计模式】_迭代器模式、JDK内置迭代器、内部类迭代器
package com.test.iterator;
/**
* 自定义的迭代器接口
*/
public interface MyIterator {
void first(); //将游标指向第一个元素
void next(); //将游标指向下一个元素
boolean hasNext(); //判断是否存在下一个元素
boolean isFirst();
boolean isLast();
Object getCurrentObj(); //获取当前游标指向的对象
}
package com.test.iterator;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义的聚合类
*/
public class ConcreteMyAggregate {
private List<Object> list = new ArrayList<Object>();
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 ConcreteIterator();
}
//使用内部类定义迭代器,可以直接使用外部类的属性
private class ConcreteIterator 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.test.iterator;
public class Client {
public static void main(String[] args) {
ConcreteMyAggregate cma = new ConcreteMyAggregate();
cma.addObject("aa");
cma.addObject("bb");
cma.addObject("cc");
MyIterator iter = cma.createIterator();
while(iter.hasNext()){
System.out.println(iter.getCurrentObj());
iter.next();
}
}
}