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

来源:互联网 发布:windows无法安装usb 编辑:程序博客网 时间:2024/06/07 12:27
  • 定义:
    顺序访问聚合对象中的各个元素,又不暴露对象中的表示
  • 概述
  • 实例(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群讨论,以免误导其他开发者!!!

阅读全文
0 0