迭代器模式

作者: 程序员丶星霖 | 来源:发表于2017-05-07 22:39 被阅读35次

迭代器模式

定义

已经是一个没落的模式,基本上没人会单独写一个迭代器。它提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节。

英文定义为:Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation .

迭代器模式的UML类图如下所示:

迭代器模式.jpg

上图中包含的角色及职责:

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

迭代器模式的示例代码如下所示:

//抽象迭代器
public interface Iterator{
    //遍历到下一个元素
    public Object next();
    //是否已经遍历到尾部
    public boolean hasNext();
    //删除当前指向的元素
    public boolean remove();
}
//具体迭代器
public class ConcreteIterator implements Iterator{
    private Vector vector = new Vector();
    //定义当前游标
    public int cursor = 0;
    @SuppressWarnings("unchecked")
    public ConcreteIterator(Vector vector){
        this.vector = vector;
    }
    //判断是否到达尾部
    public boolean hasNext(){
        if(this.cursor == this.vector.size()){
            return false;
        }else{
            return true;
        }
    }
    //返回下一个元素
    public Object next(){
        Object result = null;
        if(this.hasNext()){
            result = this.vector.get(this.cursor++);
        }else{
            result = null;
        }
        return result;
    }
    //删除当前元素
    public boolean remove(){
        this.vector.remove(this.cursor);
        return true;
    }
}
//抽象容器
public interface Aggregate{
    //是容器必然有元素的增加
    public void add(Object object);
    //减少元素
    public void remove(Object object);
    //由迭代器来遍历所有的元素
    public Iterator iterator();
}
//具体容器
public class ConcreteAggregate implements Aggregate{
    //容纳对象的容器
    private Vector vector = new Vector();
    //增加一个元素
    public void add(Object object){
        this.vector.add(object);
    }
    //返回迭代器对象
    public Iterator iterator(){
        return new ConcreteIterator(this.vector);
    }
    //删除一个元素
    public void remove(Object object){
        this.remove(object);
    }
}
//场景类
public class Client{
    public static void main(String[] args){
        //声明出容器
        Aggregate agg = new ConcreteAggregate();
        //产生对象数据放进去
        agg.add("abc");
        agg.add("def");
        agg.add("asfaf");
        //遍历
        Iterator iterator = agg.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

欢迎关注我的微信公众号

我的微信公众号.jpg

相关文章

网友评论

    本文标题:迭代器模式

    本文链接:https://www.haomeiwen.com/subject/kbedtxtx.html