迭代器模式(Iterator Pattern)提供一种方法,使得在不暴露底层实现的情况下,提供一种顺序访问一组对象的方法。Java中的Iterator.java迭代器接口就是该设计模式的体现。
一、需求举例:
遍历项目中使用的开发语言,{"Java", "Python", "C/C++", "C#", "Groovy", "Scala", "Shell"},分别做相应的处理。
二、类图:
三、代码实例:
1.迭代接口:MyIterator
package com.lance.iterator;
public interface MyIterator {
boolean hasNext();
Object next();
}
2.迭代器实现类:CodeIterator
package com.lance.iterator;
public class CodeIterator implements MyIterator{
public String codes[];
int index;
public CodeIterator(String[] codes, int index) {
this.codes = codes;
this.index = index;
}
@Override
public boolean hasNext() {
if(index < codes.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return codes[index++];
}
return null;
}
}
3.容器父类:
package com.lance.iterator;
public interface MyContainer {
MyIterator getIterator();
}
4.容器实现类:
package com.lance.iterator;
public class CodeContainer implements MyContainer {
private MyIterator iterator;
public CodeContainer(MyIterator iterator) {
this.iterator = iterator;
}
@Override
public MyIterator getIterator() {
return iterator;
}
}
5.主类:IteratorPattern
package com.lance.iterator;
public class IteratorPattern {
public static void main(String[] args) {
System.out.println("==========start==========");
String codes[] = {"Java", "Python", "C/C++", "C#", "Groovy", "Scala", "Shell"};
CodeIterator iterator = new CodeIterator(codes, 0);
CodeContainer container = new CodeContainer(iterator);
for(MyIterator myIterator=container.getIterator();myIterator.hasNext();) {
System.out.println("code language : " + myIterator.next());
}
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
code language : Java
code language : Python
code language : C/C++
code language : C#
code language : Groovy
code language : Scala
code language : Shell
==========end==========
网友评论