迭代子模式(Iterator)分析---基于JAVA语言

来源:互联网 发布:linux open 编辑:程序博客网 时间:2024/06/07 07:15

迭代子模式(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());              }          }      }  

很简单的例子让我理解迭代子模式的同时,对于集合部分迭代器的使用更加深入的理解。