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)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 鄉舉里選 西周地方選士1年舉行1次,訖至3年則舉行大考,即所謂“3年大比”。由鄉大夫總其下屬官吏的推薦,再進行1次...
    李古閱讀 1,077評論 0 0
  • 我自以為是很坦誠的人,因為覺得只有充分的溝通才能解決問題,但昨天我發現這錯得很離譜。我的坦白充滿了目的性,好像只要...
    云時之間閱讀 280評論 0 3
  • 這兩天,江歌案已經引爆了朋友圈,我無法抑制自己對于此事的一些看法,準備一吐為快。 迄今為止所知的信息為:2016年...
    林小殤閱讀 550評論 0 3
  • 序言 大一的時候,有人推薦我去學開車,我說:“我不要學開車,我這個路癡開車不靠譜。我以后坐人家的順風車?!?我朋友...
    程云舒閱讀 670評論 1 8
  • 這個故事是真實發生在我爺爺奶奶18 歲時,也就是47年前發生的事,我想把他們那個年代他們發生...
    毅駒閱讀 535評論 0 1