对象行为型模式——迭代器模式(Iterator)

版权声明:本文为博主原创文章,但部分内容来源网络,如有侵权,告知即删! https://blog.csdn.net/chenyuan_jhon/article/details/78320475
  • 定义:
    顺序访问聚合对象中的各个元素,又不暴露对象中的表示
  • 概述
  • 实例(java语言)
    迭代接口
public interface Iterator {
    /**
     * First.移动到第一个对象位置
     */
    void first();

    /**
     * Next.移动到下一个位置
     */
    void next();


    /**
     * Is done boolean.
     *
     * @return the boolean ,true 表示移动到最后一个位置了
     */
    boolean isDone();

    /**
     * Current item object.
     *
     * @return the object
     */
    Object currentItem();

}

具体迭代接口

public class ConcreteIterator implements Iterator {

    //具体聚合对象
    private ConcreteAggregate mAggregate;
    private int index = -1;//内部索引

    public ConcreteIterator(ConcreteAggregate aggregate) {
        mAggregate = aggregate;
    }

    @Override
    public void first() {
        index = 0;
    }

    @Override
    public void next() {
        if (index < this.mAggregate.size()) {
            index += 1;
        }
    }

    @Override
    public boolean isDone() {
        if (index == this.mAggregate.size()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object currentItem() {
        return this.mAggregate.get(index);
    }
}

聚合对象抽象类,定义创建相应迭代器对象的接口

public abstract class Aggregate {
    public abstract Iterator createIterator();
}

具体聚合对象,创建相应的迭代器

public class ConcreteAggregate extends Aggregate {
    private String[] ss = null;

    /**
     * Instantiates a new Concrete aggregate.
     *
     * @param ss the ss
     */
    public ConcreteAggregate(String[] ss) {
        this.ss = ss;
    }

    @Override
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }

    /**
     * Get object.
     *
     * @param index the index
     * @return the object
     */
    public Object get(int index){
        Object retObj = null;
        if (index<ss.length) {
            retObj = ss[index];
        }
        return retObj;
    }

    /**
     * Size int.
     *
     * @return the int
     */
    public int size(){
        return this.ss.length;
    }
}

client

public class Client {
    public void test(){
        String[] names = {"张三","李四","王五"};
        ConcreteAggregate aggregate = new ConcreteAggregate(names);
        Iterator iterator = aggregate.createIterator();
        iterator.first();
        while (!iterator.isDone()) {
            Object o = iterator.currentItem();
            System.out.println("the obj = "+o);
            iterator.next();
        }
    }
}

测试及结果

public class HeadFirstTest {
    public static void main(String[] args) {
        new Client().test();
    }
}
结果
the obj = 张三
the obj = 李四
the obj = 王五

Process finished with exit code 0

如有错误,请留言更正,或进580725421群讨论,以免误导其他开发者!!!

猜你喜欢

转载自blog.csdn.net/chenyuan_jhon/article/details/78320475