The iterator pattern for the Java Design Pattern series

Source: Internet
Author: User
Tags object object

Iterator pattern definition

Iterator mode (Iterator), which provides a way to sequentially access various elements in an aggregated object without exposing the object's internal representation.

Role composition of the iterator pattern

(1) Iterator Role (Iterator): Defines the methods required to traverse elements, generally there are three ways to get the next element in the next (), to determine whether to traverse the end of the method Hasnext ()), remove the current object method remove (),

(2) Specific iterator role (concrete Iterator): Implements the method defined in the iterator interface to complete the iteration of the collection.

(3) Container role (Aggregate): Typically an interface that provides a iterator () method, such as a collection interface in Java, a list interface, a set interface, and so on

(4) The specific container role (Concreteaggregate): Is the concrete implementation of the abstract container class, such as the list interface of the ordered list of Arraylist,list interface to implement the list of Linklist,set Interface hash table implementation HashSet and so on.

The scenario and significance of the application of the iterator pattern
(1) Accessing the contents of an aggregated object without exposing its internal representation

(2) Support for multiple traversal of aggregated objects

(3) Provide a unified interface iterator pattern for traversing different aggregation structures four roles relationships can be represented by a class diagram for a specific code implementation: defining an iterator Role (Iterator)
1  Public Interface Iterator {23      Public Boolean Hasnext (); 4      Public Object Next (); 5 }

Defining specific iterator roles (concrete Iterator)

1  Packagepatten.design;2 3 Importpatten.design.List;;4 5  Public classConcreteiteratorImplementsIterator {6     PrivateList List =NULL;7     Private intindex;8 9      Publicconcreteiterator (List list) {Ten         Super(); One          This. List =list; A     } -  - @Override the      Public BooleanHasnext () { -         if(Index >=list.getsize ()) { -             return false; -}Else { +             return true; -         } +     } A  at @Override -      PublicObject Next () { -Object object =List.get (index); -index++; -         returnobject; -     } in  -}

Defining container Roles (Aggregate)

1  Packagepatten.design;2 3 //define what the collection can do4  Public InterfaceList {5 6      Public voidAdd (Object obj); 7      PublicObject Get (intindex);8      PublicIterator Iterator (); 9      Public intgetsize ();Ten}

Defining specific container roles (concreteaggregate)

1  Packagepatten.design;2 3  Public classConcreteaggregateImplementslist{4 5     Privateobject[] list;6     Private intSize=0;7     Private intIndex=0;8      Publicconcreteaggregate () {9Index=0;TenSize=0; Onelist=Newobject[100]; A     } - @Override -      Public voidAdd (Object obj) { thelist[index++]=obj; -size++; -     } -  + @Override -      PublicIterator Iterator () { +          A         return NewConcreteiterator ( This); at     } - @Override -      PublicObject Get (intindex) { -          -         returnList[index]; -     } in @Override -      Public intGetSize () { to          +         returnsize; -     } the  *}

Code testing

1  Packagepatten.design;2 3  Public classIteratortest {4 5     /**6      * @paramargs7      */8      Public Static voidMain (string[] args) {9 TenList list=Newconcreteaggregate (); OneList.add ("a"); AList.add ("B"); -List.add ("C"); -List.add ("D"); theIterator it=list.iterator (); -          while(It.hasnext ()) { - System.out.println (It.next ()); -         } +     } -  +}

Advantages and disadvantages of the iterator pattern:

The advantages of the iterator pattern are:

    • Simplified traversal method, for the object collection of traversal, or more cumbersome, for arrays or have a sequence of tables, we can still get through the cursor, but users need to understand the set is very clear premise, self-traversal objects, but for the hash table, the user traversal is more troublesome. With the introduction of the iterator method, the user is much simpler to use.
    • can provide a variety of traversal methods, such as the sequence of the table, we can provide a positive sequence traversal, reverse-traverse the two iterators, the user only need to get our implementation of a good iterator, we can easily traverse the collection.
    • Encapsulation is good, users only need to get iterators to traverse, and for the traversal algorithm is not to care.

Disadvantages of the iterator pattern:

    • For a simpler traversal (like an array or a sequence table), it's tedious to iterate with an iterator, and everyone might feel like ArrayList, and we'd rather use the for loop and get methods to iterate through the collection.

Overall: The iterator pattern is associated with the collection, in general, as long as we implement a set, we need to provide this set of iterators, like Java collection,list, set, map, and so on, these collections have their own iterators. If we were to implement a new container like this, we would certainly need to introduce an iterator pattern to implement an iterator to our container.

The iterator pattern for the Java Design Pattern series

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.