Design mode-iterator mode (Iterator pattern)

Source: Internet
Author: User
Tags iterable

This article by @ Stay for the original, reproduced please indicate source: http://www.cnblogs.com/coffeeSS/

Introduction to the iterator pattern

Iterators believe that most people are not strangers, and that the container classes of many programming languages, such as java/c++, support iterator operations, a pattern that describes the details of an iterator implementation.

The definition and basic structure of the iterator pattern

Definition: provides a method that can sequentially access individual elements in an aggregation object with an internal implementation of the non-exposed device.

A structure drawing from Head first.

client: call iterator to iterate over the elements within the concreteaggregate without requiring a specific structure concreteaggregate the relationship.

Concreteaggregate: A representative of some kind of aggregation class, such as ArrayList.

Concreteiterator: an iterator class associated with an aggregation class that implements the iterator interface, each of which has a corresponding concreteiterator for each specific aggregation class type.

Iterator: This interface contains the general method of the iterator.

Aggregate: contains the Createiterator () method, which inherits this interface to indicate that the aggregation class supports iterators, and calls the Createiterator () method to obtain the iterator.

A simple instance (Java)

Instead of an example, let's implement an iterator for ArrayList when the practice is good.

Let's start by writing a new class, wrap the ArrayList, call myArrayList, and implement an iterator for myarraylist.

myArrayList will inherit a iterable interface, which is provided by Java, and implements this interface to indicate that the aggregation class supports iterators, just like the aggregate function in the above structure, except that the Iterable method is called iterator (). The code is as follows.

1 Importjava.util.ArrayList;2 ImportJava.util.Iterator;3  Public classmyArrayListImplementsIterable<string> {4Arraylist<string>arrayList;5     intPosition=0;6      Publicmyarraylist () {7arraylist=NewArraylist<string>();8     }9      Public voidAddItem (String s) {Ten Arraylist.add (s); One     } A      Public voidRemoveItem (intindex) { - Arraylist.remove (index); -     } the      Public intsize () { -         returnarraylist.size (); -     } -      PublicString GetItem (intindex) { +         returnArraylist.get (index); -     } + @Override A      PublicIterator<string>iterator () { at         return NewMyarraylistiterator ( This); -     } -}

After implementing the Myarraylistiterator class, which is the Concreteiterator class in the structure diagram, he inherits the iterator interface provided by Java, which has Hasnext (), Next (), remove () Three methods that need to be implemented, We can achieve the first two to complete the iteration, the third to throw an exception directly, we can also implement their own, anyway very simple.

1 ImportJava.util.Iterator;2  Public classMyarraylistiteratorImplementsIterator<string> {3 myarraylist myarraylist;4     intPosition=0;5      PublicMyarraylistiterator (myarraylist m) {6myarraylist=m;7     }8 @Override9      Public BooleanHasnext () {Ten         if(Myarraylist.size () >position) One             return true; A         return false; -     } - @Override the      PublicString Next () { -         returnMyarraylist.getitem (position++); -     } - @Override +      Public voidRemove () { -         Throw Newunsupportedoperationexception (); +     } A}

The test code is as follows.

1 ImportJava.util.Iterator;2  Public classTest {3      Public Static voidMain (string[] args) {4myArrayList m=Newmyarraylist ();5M.additem ("First");6M.additem ("Second");7M.additem ("Tired");8M.additem ("Fourth");9M.additem ("Fifth");TenIterator<string> it=m.iterator (); One          while(It.hasnext ()) { A System.out.println (It.next ()); -         }     -     } the}

The output is as follows:

About the For/in statement (Java 5)

After Java 5, Java gives a new for statement that lets us iterate over aggregate classes, as long as the aggregation classes that support iterator can iterate with such statements, such as the following

1 ImportJava.util.Iterator;2  Public classTest {3      Public Static voidMain (string[] args) {4myArrayList m=Newmyarraylist ();5M.additem ("First");6M.additem ("Second");7M.additem ("Tired");8M.additem ("Fourth");9M.additem ("Fifth");TenIterator<string> it=m.iterator (); One //While (It.hasnext ()) { A //System.out.println (It.next ()); - //        }     -          for(String s:m) { the System.out.println (s); -         } -     } -}

There is no difference between the output and the above.

This is the end of the iterator pattern, which is so familiar to programmers, super simple right? (^∇^*).

Reference: "Head first design mode".

Design mode-iterator mode (Iterator pattern)

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.