Iterator Pattern

The Iterator Pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. The C++ and Java standard library abstraction utilize it to decouple collection classes and algorithms.

Intent

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Implementation

Class Diagram of Iterator Pattern

Here is an example using Iterator Pattern to retrieve the names of all the pets in the pet repository.

Create interfaces.

// Iterator.java
public interface Iterator {

    boolean hasNext();
    Object next();
}
// Container.java
public interface Container {

    Iterator getIterator();
}

Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface.

// PetRepository.java
public class PetRepository implements Container {

    public String pets[] = {
            "Tyrannosaurus Rex",
            "Stegosaurus",
            "Velociraptor",
            "Triceratops",
            "Pterosauria",
            "Ichthyosaur",
            "Tanystropheus"};

    @Override
    public Iterator getIterator() {
        return new NameIterator();
    }

    private class NameIterator implements Iterator {

        int index = 0;

        @Override
        public boolean hasNext() {
            return index < pets.length;
        }

        @Override
        public Object next() {

            if (hasNext()) {
                return pets[index++];
            }
            return null;
        }
    }
}

Let's print out our lovely pets ;)

// ClientMain.java
public class ClientMain {

    public static void main(String[] args) {

        PetRepository pets = new PetRepository();

        for (Iterator iter = pets.getIterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            System.out.println(name);
        }
    }
}

Output

Tyrannosaurus Rex
Stegosaurus
Velociraptor
Triceratops
Pterosauria
Ichthyosaur
Tanystropheus

Reference

TutorialsPoint
OODesign
Hackjustu Dojo (my blog)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 乡举里选 西周地方选士1年举行1次,讫至3年则举行大考,即所谓“3年大比”。由乡大夫总其下属官吏的推荐,再进行1次...
    李古阅读 4,966评论 0 0
  • 我自以为是很坦诚的人,因为觉得只有充分的沟通才能解决问题,但昨天我发现这错得很离谱。我的坦白充满了目的性,好像只要...
    云时之间阅读 2,350评论 0 3
  • 这两天,江歌案已经引爆了朋友圈,我无法抑制自己对于此事的一些看法,准备一吐为快。 迄今为止所知的信息为:2016年...
    林小殇阅读 3,624评论 0 3
  • 序言 大一的时候,有人推荐我去学开车,我说:“我不要学开车,我这个路痴开车不靠谱。我以后坐人家的顺风车。” 我朋友...
    程云舒阅读 3,868评论 1 8
  • 这个故事是真实发生在我爷爷奶奶18 岁时,也就是47年前发生的事,我想把他们那个年代他们发生...
    毅驹阅读 3,526评论 0 1

友情链接更多精彩内容