The iterator pattern for the Java Design Pattern series

Source: Internet
Author: User

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):

Define the methods required to traverse the elements, generally there are three methods:

Get the next element method next (),

The method of determining whether to traverse the end Hasnext ()),

Remove the method from the current object, 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):

is typically an interface that provides a iterator () method,

such as the collection interface in Java, the list interface, the set interface, etc.

(4) Specific container role (concreteaggregate):

is the concrete implementation class of the abstract container,

For example, the list interface of the ordered list implementation of the Arraylist,list interface to implement the Linklist,set interface hash list 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) Providing a unified interface iterator for traversing different aggregation structures four roles relationships can be represented by class diagrams Specific code implementation:Defining an iterator role (Iterator)
1 public interface Iterator {2 3 publicly     Boolean hasnext (); 4 public     Object Next (); 5}

Defining specific iterator roles (concrete Iterator)

1 package patten.design; 2  3 import patten.design.List;; 4  5 public class Concreteiterator implements Iterator {6     private list List = Null 7     private int index; 8  9 public     concreteiterator (List list) {Ten         super ();         this.list = list;12     }13     @Override15 public     boolean hasnext () {         if (index >= list.getsize ()) {+             return False;18         } else {             return true;20         }21     }22 @Override24 public     Object next () {25         Object object = List.get (index);         index++;27         return object;28     }29 30}

Defining container Roles (Aggregate)

1 package patten.design; 2  3//define what the collection can do 4 public interface List {5  6 public     void Add (Object obj);   7 Public     Object get (int index), 8 public     Iterator Iterator ();   9 Public     int GetSize (); 10}

Defining specific container roles (concreteaggregate)

1 package patten.design; 2  3 public class Concreteaggregate implements list{4  5     private object[] List; 6     private int size=0; 7
   
    private int index=0; 8 public     Concreteaggregate () {9         index=0;10         size=0;11         list=new object[100];12     }13     @ OVERRIDE14 public     void Add (Object obj) {         list[index++]=obj;16         size++;17     }18     @ Override20 public     Iterator Iterator () {"         return to New Concreteiterator (this)",     }24     @ Override25 public     Object get (int index) {         list[index];28 return     }29     @Override30     public int GetSize () {         return size;33     }34 35}
   

Code testing

1 package patten.design; 2  3 public class Iteratortest {4  5     /** 6      * @param args 7      */8 public     static void Main (string[] Ar GS) {9         List list=new concreteaggregate (),         list.add ("a"),         list.add ("B"),         List.add ("C"); 14         List.add ("D");         Iterator It=list.iterator (); (         It.hasnext ()) {             System.out.println (It.next ());         }19     }20 21}

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.