行为型模式:4.迭代子模式(Iterator)

顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。这句话包含两层意思:一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。

两个接口:

1.public interface Collection {  
2.      
3.    public Iterator iterator();  
4.      
5.    /*取得集合元素*/  
6.    public Object get(int i);  
7.      
8.    /*取得集合大小*/  
9.    public int size();  
10.}  
1.public interface Iterator {  
2.    //前移  
3.    public Object previous();  
4.      
5.    //后移  
6.    public Object next();  
7.    public boolean hasNext();  
8.      
9.    //取得第一个元素  
10.    public Object first();  
11.}  
两个实现:

1.public class MyCollection implements Collection {  
2.  
3.    public String string[] = {“A”,”B”,”C”,”D”,”E”};  
4.    @Override  
5.    public Iterator iterator() {  
6.        return new MyIterator(this);  
7.    }  
8.  
9.    @Override  
10.    public Object get(int i) {  
11.        return string[i];  
12.    }  
13.  
14.    @Override  
15.    public int size() {  
16.        return string.length;  
17.    }  
18.}  
1.public class MyIterator implements Iterator {  
2.  
3.    private Collection collection;  
4.    private int pos = -1;  
5.      
6.    public MyIterator(Collection collection){  
7.        this.collection = collection;  
8.    }  
9.      
10.    @Override  
11.    public Object previous() {  
12.        if(pos > 0){  
13.            pos–;  
14.        }  
15.        return collection.get(pos);  
16.    }  
17.  
18.    @Override  
19.    public Object next() {  
20.        if(pos<collection.size()-1){  
21.            pos++;  
22.        }  
23.        return collection.get(pos);  
24.    }  
25.  
26.    @Override  
27.    public boolean hasNext() {  
28.        if(pos<collection.size()-1){  
29.            return true;  
30.        }else{  
31.            return false;  
32.        }  
33.    }  
34.  
35.    @Override  
36.    public Object first() {  
37.        pos = 0;  
38.        return collection.get(pos);  
39.    }  
40.  
41.}  
测试类:

1.public class Test {  
2.  
3.    public static void main(String[] args) {  
4.        Collection collection = new MyCollection();  
5.        Iterator it = collection.iterator();  
6.          
7.        while(it.hasNext()){  
8.            System.out.println(it.next());  
9.        }  
10.    }  
11.}  
输出:A B C D E

此处我们貌似模拟了一个集合类的过程,感觉是不是很爽?其实JDK中各个类也都是这些基本的东西,加一些设计模式,再加一些优化放到一起的,只要我们把这些东西学会了,掌握好了,我们也可以写出自己的集合类,甚至框架!

posted @ 2016-08-30 11:05  wangkejun  阅读(141)  评论(0)    收藏  举报