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

  • 定义:
    顺序访问聚合对象中的各个元素,又不暴露对象中的表示
  • 概述
  • 实例(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群讨论,以免误导其他开发者!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值