迭代子模式(Iterator)
顧名思義,迭代器模式就是順序訪問聚集中的對象,一般來說,集合中非常常見,因此我通過一個小例子來研究迭代子模式,研究設計模式的同時,更好的掌握集合中的迭代器使用.
例子:1.定義一個Collection接口:
public interface Collection {
public Iterator iterator();
/*取得集合元素*/
public Object get(int i);
/*取得集合大小*/
public int size();
}
2.定義一個Iterator接口:
public interface Iterator {
//前移 上一個元素
public Object previous();
//後移 下一個元素
public Object next();
public boolean hasNext();
//取得第一個元素
public Object first();
}
3. 定義一個類來實現Collection接口:
public class MyCollection implements Collection {
//假設這個集合內部是由數組實現
public String string[] = {"A","B","C","D","E"};
public Iterator iterator() {
return new MyIterator(this);
}
public Object get(int i) {
return string[i];
}
public int size() {
return string.length;
}
}
4.定義一個類來實現Iteraotr接口
//這個地方其實一般會設計爲內部類
public class MyIterator implements Iterator {
private Collection collection;
private int pos = -1;
public MyIterator(Collection collection){
this.collection = collection;
}
public Object previous() {
if(pos > 0){
pos--;
}
return collection.get(pos);
}
public Object next() {
if(pos<collection.size()-1){
pos++;
}
return collection.get(pos);
}
public boolean hasNext() {
if(pos<collection.size()-1){
return true;
}else{
return false;
}
}
public Object first() {
pos = 0;
return collection.get(pos);
}
}
5.測試一下:
//測試類
public class Test {
public static void main(String[] args) {
Collection collection = new MyCollection();
Iterator it = collection.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
很簡單的例子讓我理解迭代子模式的同時,對於集合部分迭代器的使用更加深入的理解。