标签:
public interface Iterator{
public boolean hasNext();
publicObject next();
}
public interface Container{
publicIterator getIterator();
}
publicclassNameRepository implements Container{
publicString names[]={"Robert","John","Julie","Lora"};
@Override
publicIterator getIterator(){
returnnewNameIterator();
}
privateclassNameIterator implements Iterator{//分离了集合对象的遍历行为,抽象出一个迭代器类来负责
int index;
@Override
public boolean hasNext(){
if(index < names.length){
returntrue;
}
returnfalse;
}
@Override
publicObject next(){
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
publicclassIteratorPatternDemo{
publicstaticvoid main(String[] args){
NameRepository namesRepository =newNameRepository();
for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
String name =(String)iter.next();
System.out.println("Name : "+ name);
}
}
}
标签:
原文地址:http://www.cnblogs.com/Doing-what-I-love/p/5621162.html