美文网首页程序员
Iterator Pattern

Iterator Pattern

作者: Hackjutsu | 来源:发表于2016-04-12 05:51 被阅读72次

    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)

    相关文章

      网友评论

        本文标题:Iterator Pattern

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