迭代模式:
此模式的思想是有一个数据集合,我们写出一个算法集合,使用算法集合内的各个算法,来迭代数据集合,获得一些数据。
最常见的就是 List 、Set 等我们常常使用的集合,采用迭代器(Iterator)进行获取集合内的元素。
以下模仿写了一个实现
package com.mkf.pattern;
public interface Iterator {
public Object previous();
public boolean hasPrevious();
public Object next();
public boolean hsNext();
public Object first();
public boolean isFirst();
public Object last();
public boolean isLast();
}
package com.mkf.pattern;
public interface Collection {
public Iterator getIterator();
public Object get(int i);
public int size();
}
package com.mkf.pattern.impl;
import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;
public class MyIterator implements Iterator {
private Collection collection;
private int pos = -1;
public MyIterator(Collection collection) {
this.collection = collection;
}
@Override
public Object first() {
pos = 0;
return collection.get(pos);
}
@Override
public boolean isFirst() {
if (pos == 0) {
return true;
}
return false;
}
@Override
public Object last() {
pos = collection.size() - 1;
return collection.get(pos);
}
@Override
public boolean isLast() {
if (pos == collection.size() - 1) {
return true;
}
return false;
}
@Override
public Object next() {
if (pos < collection.size() - 1) {
pos++;
}
return collection.get(pos);
}
@Override
public boolean hsNext() {
if (pos < collection.size() - 1) {
return true;
}
return false;
}
@Override
public boolean hasPrevious() {
if (pos > 0) {
return true;
}
return false;
}
@Override
public Object previous() {
if (pos > 0) {
pos--;
}
return collection.get(pos);
}
}
package com.mkf.pattern.impl;
import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;
public class MyCollection implements Collection {
public String[] str = { "A", "B", "C", "D", "E", "F", "G" };
@Override
public Object get(int i) {
return str[i];
}
@Override
public Iterator getIterator() {
return new MyIterator(this);
}
@Override
public int size() {
return str.length;
}
}
package com.mkf;
import com.mkf.pattern.Collection;
import com.mkf.pattern.Iterator;
import com.mkf.pattern.impl.MyCollection;
public class TestIterator {
/**
* @param args
*/
public static void main(String[] args) {
Collection collection = new MyCollection();
Iterator iterator = collection.getIterator();
while(iterator.hsNext()){
System.out.print(iterator.next());
System.out.print("\t");
}
}
}
运行结果为:
A B C D E F G