Design mode-iterator mode (Iterator)

Source: Internet
Author: User

The ability to walk through each element within the aggregation, while also providing a variety of different traversal methods .

 Basic Concepts: is to provide a way to sequentially access individual elements in an aggregated object, rather than exposing their internal representations .
 advantages of using the iterator pattern:
    1. Iterate over a set or array;
    2. Ignores the structure of sets and arrays;
    3. Provide a different way to traverse;
    4. Conforms to the principle of single responsibility.
iterator role:
      1. Abstract iterator: The interface must define a set of minimum defined methods that implement iterative functionality.
      2. Specific iterator: an implementation class for the iterator interface iterator. Can be implemented according to specific circumstances.
      3. Abstract aggregation classes: define basic functions and provide methods similar to iterator iterator ().
      4. Specific aggregation class: the implementation class for the container interface. The iterator iterator () method must be implemented.

Book.java

 PackageCom.soyoungboy.iterator2; Public classBook {PrivateString ISBN; PrivateString name; Private DoublePrice ;  PublicBook (string ISBN, string name,DoublePrice ) {ISBN=ISBN;  This. Name =name;  This. Price =Price ; }     PublicString getisbn () {returnISBN; }     Public voidSETISBN (String ISBN) {ISBN=ISBN; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public DoubleGetPrice () {returnPrice ; }     Public voidSetprice (DoublePrice ) {         This. Price =Price ; }         Public voiddisplay () {System.out.println ("isbn=" + ISBN + ", name=" + name + ", price" +Price ); }        }

Abstract iterator Iterator.java

 Public Interface Iterator {    boolean  hasnext ();    Object next ();     void remove ();

Specific iterators ITR Specific aggregation classes Booklist.java

 PackageCom.soyoungboy.iterator2;Importjava.util.ArrayList;Importjava.util.List; Public classBooklist {PrivateList<book>Booklist; Private intindex;  PublicBooklist () {Booklist=NewArraylist<book>(); }        //Add a book     Public voidAddbook {booklist.add (book); }        //Delete a book     Public voidDeletebook (book book) {intBookindex =booklist.indexof (book);    Booklist.remove (Bookindex); }             PublicIterator Iterator () {return NewItr (); }        /*** Specific iterators *@authorSoyoungboy **/    Private classItrImplementsiterator{ Public BooleanHasnext () {if(Index >=booklist.size ()) {                return false; }            return true; }         PublicObject Next () {returnBooklist.get (index++); }         Public voidremove () {}}}

Test code class: Mainclass.java

 PackageCom.soyoungboy.iterator2; Public classMAINCLSS { Public Static voidMain (string[] args) {Booklist Booklist=NewBooklist (); Book Book1=NewBook ("010203", "Java Programming ideas", 90); Book Book2=NewBook ("010204", "Java from getting started to mastering", 60);        Booklist.addbook (BOOK1);        Booklist.addbook (BOOK2); Iterator ITER=Booklist.iterator ();  while(Iter.hasnext ()) { Book Book=(book) Iter.next ();        Book.display (); }    }}
Running results: Isbn=010203,name=java programming ideas, Price90.0isbn=010204,name=java from beginner to proficient, price60.0Usage Scenarios:data collection Traversal in Java usually uses the iterative design pattern for the data traversal process;Some source code can refer to: http://www.cnblogs.com/wjun530/archive/2007/06/11/778709.html this blog post for analysissuch as through the Hashtable.elements method can get a enumeration, and then through this enumeration access to the data in the Hashtable, without concern about the data storage in Hashtable. You can also use the iterator design pattern if you have the following business requirements:access the internal objects contained in the container;accessed sequentially.  Reference Documents:http://blog.sina.com.cn/s/blog_6e5e78bf0101owrq.html

Design mode-iterator mode (Iterator)

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.