设计模式(16)-迭代器模式(Iterator)

来源:互联网 发布:c语言强制类型转换规则 编辑:程序博客网 时间:2024/05/21 11:13

设计模式(15)-观察者模式(Observer)

     16、迭代器模式(Iterator)
         顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。
         例子:   

public interface Collection {          public Iterator iterator();          /*取得集合元素*/          public Object get(int i);          /*取得集合大小*/          public int size();      }    
  public interface Iterator {          //前移  上一个元素        public Object previous();                    //后移  下一个元素        public Object next();          public boolean hasNext();                    //取得第一个元素          public Object first();      }     
 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;          }      }     
 //这个地方其实一般会设计为内部类    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);          }      }   
 //测试类    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());              }          }      }  



0 0
原创粉丝点击