迭代器模式已经被淘汰,java中已经把迭代器运用到各个聚集类(collection)中了,使用java自带的迭代器就已经满足我们的需求了

概述

迭代子模式提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。顺序访问聚集中的对象,一般来说,集合中非常常见。一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。

涉及角色

  • Iterator
    抽象迭代器:抽象迭代器负责定义访问和遍历元素的接口,而且基本上是有固定的3个方法:first()获得第一个元素,next()访问下一个元素,isDone()是否已经访问到底部(Java叫做hasNext()方法)。
  • ConcreteIterator
    具体迭代器:具体迭代器角色要实现迭代器接口,完成容器元素的遍历。
  • Aggregate
    抽象容器:容器角色负责提供创建具体迭代器角色的接口,必然提供一个类似createIterator()这样的方法,在Java中一般是iterator()方法。
  • Concrete Aggregate
    具体容器:具体容器实现容器接口定义的方法,创建出容纳迭代器的对象。

UML

这里写图片描述

代码示例

package com.designpattern.iterator;

public interface Collection {
    public Iterator iterator();

    /* 取得集合元素 */
    public Object get(int i);

    /* 取得集合大小 */
    public int size();
}
package com.designpattern.iterator;

public interface Iterator {
    public Object previous();  

    //后移  
    public Object next();  
    public boolean hasNext();  

    //取得第一个元素  
    public Object first();   
}
package com.designpattern.iterator;

public class MyCollection implements Collection {
    public String string[] = {"A","B","C","D","E"};  
    @Override  
    public Iterator iterator() {  
        return new MyIterator(this);  
    }  

    @Override  
    public Object get(int i) {  
        return string[i];  
    }  

    @Override  
    public int size() {  
        return string.length;  
    }  

}
package com.designpattern.iterator;

public class MyIterator implements Iterator {

    private Collection collection;
    private int pos = -1;

    public MyIterator(Collection collection) {
        this.collection = collection;
    }

    @Override
    public Object previous() {
        if (pos > 0) {
            pos--;
        }
        return collection.get(pos);
    }

    @Override
    public Object next() {
        if (pos < collection.size() - 1) {
            pos++;
        }
        return collection.get(pos);
    }

    @Override
    public boolean hasNext() {
        if (pos < collection.size() - 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object first() {
        pos = 0;
        return collection.get(pos);
    }

}
package com.designpattern.iterator;

public class TestMain {
    public static void main(String[] args) {
        Collection collection = new MyCollection();
        Iterator it = collection.iterator();

        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐