参考这篇博客http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
字符串数组集合,Collection中的iterator()方法返回自己定义的Iterator类,用到了工厂方法。迭代器模式将集合的存储和迭代分开,符合单一职责的原则。
代码如下
public class Main {
public static void main(String[] args) {
MyCollection myCollection = new MyCollection();
Iterator iterator = myCollection.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//System.out.println(iterator.first());
//System.out.println(iterator.next());
}
}
interface Collection{
Iterator iterator(); //工厂模式
String get(int pos);
int size();
}
interface Iterator{
String next();
boolean hasNext();
String previous();
String first();
}
class MyIterator implements Iterator{
private Collection collection;
private int pos = -1;
public MyIterator(Collection collection) {
this.collection = collection;
}
@Override
public String next() {
if (pos < collection.size() -1){
++pos;
}
return collection.get(pos);
}
@Override
public boolean hasNext() {
if (pos < collection.size() -1){
return true;
}
else return false;
}
@Override
public String previous() {
if (pos > 0){
--pos;
}
return collection.get(pos);
}
@Override
public String first() {
pos = 0;
return collection.get(pos);
}
}
class MyCollection implements Collection{
String[] string = {"A","B","C","D","E"};
@Override
public Iterator iterator() {
return new MyIterator(this);
}
@Override
public String get(int pos) {
return string[pos];
}
@Override
public int size() {
return string.length;
}
}