/**
* 迭代器模式。
* @author Bright Lee
*/
public class IteratorPattern {
public static void main(String[] args) {
String[] strings = new String[] {
"红烧肉",
"鱼香肉丝",
"毛血旺"
};
Iterator<String> it = new StringIterator(strings);
while (it.hasNext()) {
String string = it.next();
System.out.println(string);
}
}
}
/**
* 迭代器接口。
*/
interface Iterator<T> {
public boolean hasNext();
public T next();
}
/**
* 迭代器。
*/
class StringIterator implements Iterator<String> {
private int index;
private String[] strings;
public StringIterator(String[] strings) {
this.strings = strings;
this.index = 0;
}
public boolean hasNext() {
if (index >= strings.length) {
return false;
}
return true;
}
public String next() {
String string = strings[index];
index++;
return string;
}
}
运行结果:
红烧肉
鱼香肉丝
毛血旺
榴芒客服系统:https://blog.youkuaiyun.com/look4liming/article/details/83146776
本文介绍了一种常用的设计模式——迭代器模式,并通过一个简单的Java示例展示了如何使用迭代器模式来遍历集合。迭代器模式提供了一种访问聚合对象中元素的方法,而无需暴露其底层表示。

被折叠的 条评论
为什么被折叠?



