美文网首页
行为型模式:17-迭代器模式

行为型模式:17-迭代器模式

作者: 综合楼 | 来源:发表于2021-06-15 22:17 被阅读0次

迭代器模式(Iterator Pattern):
提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor)。
迭代器模式是一种对象行为型模式。

image.png

在迭代器模式结构图中包含如下几个角色:

● Iterator(抽象迭代器):它定义了访问和遍历元素的接口,声明了用于遍历数据元素的方
法,例如:用于获取第一个元素的first()方法,用于访问下一个元素的next()方法,用于判断是
否还有下一个元素的hasNext()方法,用于获取当前元素的currentItem()方法等,在具体迭代器
中将实现这些方法。

● ConcreteIterator(具体迭代器):它实现了抽象迭代器接口,完成对聚合对象的遍历,同时
在具体迭代器中通过游标来记录在聚合对象中所处的当前位置,在具体实现时,游标通常是
一个表示位置的非负整数。

● Aggregate(抽象聚合类):它用于存储和管理元素对象,声明一个createIterator()方法用于
创建一个迭代器对象,充当抽象迭代器工厂角色。

● ConcreteAggregate(具体聚合类):它实现了在抽象聚合类中声明的createIterator()方法,该
方法返回一个与该具体聚合类对应的具体迭代器ConcreteIterator实例。


image.png

JavaIterator

public class IteratorDemo {
    public static void process(Collection c) {
        Iterator i = c.iterator();

        while (i.hasNext()) {
            System.out.println(i.next().toString());
        }
    }

    public static void main(String args[]) {
        Collection list = new HashSet();
        list.add("Cat");
        list.add("Dog");
        list.add("Pig");
        list.add("Dog");
        list.add("Monkey");

        process(list);
    }
}

SimpleIterator

package com.zhs.design.Iterator.SimpleIterator;

interface MyCollection {
    MyIterator createIterator();
}
-----------------------------------------------------------------------------
interface MyIterator {
    void first();

    void next();

    boolean isLast();

    Object currentItem();
}
-----------------------------------------------------------------------------
class NewCollection implements MyCollection {
    private Object[] obj = {"dog", "pig", "cat", "monkey", "pig"};

    public MyIterator createIterator() {
        return new NewIterator();
    }

    private class NewIterator implements MyIterator {
        private int currentIndex = 0;

        public void first() {
            currentIndex = 0;
        }

        public void next() {
            if (currentIndex < obj.length) {
                currentIndex++;
            }
        }

        public void previous() {
            if (currentIndex > 0) {
                currentIndex--;
            }
        }

        public boolean isLast() {
            return currentIndex == obj.length;
        }

        public boolean isFirst() {
            return currentIndex == 0;
        }

        public Object currentItem() {
            return obj[currentIndex];
        }

    }
}
-----------------------------------------------------------------------------
class Client {
    public static void process(MyCollection collection) {
        MyIterator i = collection.createIterator();

        while (!i.isLast()) {
            System.out.println(i.currentItem().toString());
            i.next();
        }
    }

    public static void main(String a[]) {
        MyCollection collection = new NewCollection();
        process(collection);
    }
}

相关文章

网友评论

      本文标题:行为型模式:17-迭代器模式

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