Java Design Pattern Learning record-iterator mode

Source: Internet
Author: User

Objective

This time to introduce the iterator pattern, is also a behavior pattern. I now think that blogging a bit to deal with, before the day an article, feel this actually a bit did not understand a thorough written down, and after writing himself did not read a few times, the last time in the interview was asked to Java I/O in various implementations of what design mode, I Leng want to come out for half a day, I also did not want to come out, the last is the interviewer to give the answer, is the decoration mode, heard the answer after the Epiphany, the first two days just saw the decoration mode, but also write down the I/O operation of the various classes are used in the decorative mode, and then think of two reasons caused by the time did not answer, First, the interview tense is easy to remember, the second is the design pattern of understanding or not thorough. So I would rather write a blog slowly also to write their own things understand thoroughly.

Introduction to the concept of iterator patterns

iterator mode, also known as cursor mode. This pattern provides a way to access individual elements in a container object without exposing the object's internal details . This pattern is also common in our daily development, such as the following scenario:

        java.util.iterator<string> it = list.iterator ();                  while (It.hasnext ()) {            //using "it.next ();" Do some business logic        }

This is easier to understand, and the following is the implementation of the iterator pattern through specific scenario examples.

Example

There are several books on a bookshelf, and now I want to know what books are on the shelves and print out the titles. Then the bookshelf can have the function of iteration, and can iterate over all the books it holds. Implemented in code as follows:

Defines an iterator interface that contains methods to detect if there is a next element and how to get the next element

 /**   * iterator interface   public  interface   Iterator { /**   * detect if there is a next element *  @return  */ public  abstract  boolean   Hasnext ();  /**   * get Next element *   @return  */ public  abstract   Object Next ();}  

Defines an interface that contains an iterator object

/***/Publicinterface  Aggregate    {/**     * Get iterator object      @return     */public    abstract  Iterator Iterator ();}

Book category

/*** Book category*/ Public classBook {//Book name    PrivateString name = "";  PublicBook (String name) { This. Name =name; }    /*** Get the name of the book *@return     */     PublicString GetName () {returnname; }}

Bookshelf Class

/*** Bookshelf Class*/ Public classBookshelfImplementsaggregate{Privatebook[] Books; Private intLast = 0;  PublicBookshelf (intmaxSize) {         This. Books =NewBook[maxsize]; }    /*** Get Books *@paramIndex *@return     */     PublicBook Getbookat (intindex) {        returnBooks[index]; }    /*** Add a book *@param Book*/     Public voidAppendbook (book book) { This. books[last] =Book ; Last++; }    /*** Get the number of books on the bookshelf *@return     */     Public intGetLength () {returnbooks.length; }    /*** Get Bookshelf Iterator Object *@return     */@Override PublicIterator Iterator () {return NewBookshelfiterator ( This); }}

Bookshelf Iterators

/*** Bookshelf Iterator*/ Public classBookshelfiteratorImplementsIterator {PrivateBookshelf Bookshelf; Private intindex;  PublicBookshelfiterator (Bookshelf bookshelf) { This. Bookshelf =Bookshelf;  This. index = 0; }    /*** Check if there is a next book *@return     */@Override Public BooleanHasnext () {if(index<bookshelf.getlength ()) {            return true; }Else {            return false; }    }    /*** Return to the next book *@return     */@Override PublicObject Next () { Book Book=Bookshelf.getbookat (index); Index++; returnBook ; }}

Test class

 Public classClient { Public Static voidMain (string[] args) {//Create a BookshelfBookshelf Bookshelf =NewBookshelf (5); //add a book to the BookshelfBookshelf.appendbook (NewBook ("In-depth understanding of Java virtual machines")); Bookshelf.appendbook (NewBook ("Java Programming ideas")); Bookshelf.appendbook (NewBook ("High-performance MySQL")); Bookshelf.appendbook (NewBook ("Effective Java Chinese Version")); Bookshelf.appendbook (NewBook ("Data Structure and algorithm analysis Java language description")); //Get Bookshelf iteratorsIterator Iterator =Bookshelf.iterator (); //Iteration         while(Iterator.hasnext ()) { Book Book=(book) Iterator.next ();        System.out.println (Book.getname ()); }    }}

Run results

Deep understanding Java Virtual Machine Java programming Ideas high Performance mysqleffective Java Chinese version data structure and algorithm analysis Java language description

The above example is the implementation of the iterator pattern, it can be seen in the client and the container to add an iterator, which is good to avoid the internal details of the container exposure, but also make the design in line with the "single responsibility principle."

Structure of the iterator pattern

The iterator pattern consists primarily of the following roles

Abstract iterator Role (Iterator): An abstract iterator role defines an interface for accessing and traversing elements. The iterator interface in the example above is the representative of this role.

specific iterator role (concrete Iterator): The specific iterator role is to implement the iterator interface and to record the current position in the traversal. In the example above, the Bookshelfiterator class is the representative of this role.

container Role (Aggregate): The container role is responsible for providing the interface that creates the specific iterator role. The aggregate interface in the example above represents this role.

specific container role (concrete Aggregate): The specific container role implements the interface that creates the specific iterator role, which is related to the structure of the container. The above example Bookshelf Class bookshelf

This is the role that is represented.

Summarize

The iterator pattern is a very high-frequency design pattern that allows the traversal of data to be detached from the aggregation object by introducing an iterator, which is only responsible for storing the data, and the traversal data is done by the iterator implementation. The Java language Class library has implemented the iterator pattern, in the actual development we directly use the already defined iterators, such as list, set and other sets can be used directly.

Advantages

1. It supports traversing an aggregate object in different ways, and multiple traversal methods can be defined on the same aggregate object. Replace iterators to toggle traversal methods.

2, the iterator simplifies the aggregation class. Aggregation objects can not provide traversal methods themselves.

3, in the iterator mode due to the introduction of the abstraction layer, the addition of new aggregation classes and iterator classes are very convenient, no need to modify the original code, to meet the "open and close principle" requirements.

Disadvantages

1, because the iterator pattern separates the responsibility of storing data and traversing data, adding new aggregation classes needs to add new iterators, and the number of classes increases, which increases the complexity of the system to some extent.

2, abstract iterator design is relatively large, need to fully consider the future expansion of the system, such as the JDK built-in iterator iterator can not achieve reverse traversal, if the need to implement reverse traversal, only through its subclass listiterator, etc. to achieve, The Listiterator iterator cannot be used to manipulate aggregate objects of the set type.

Applicable scenarios

You may consider using the iterator pattern in the following situations

1. Access the contents of an aggregated object without exposing its internal representation. Separating the access of the aggregated object from the storage of the internal data makes it unnecessary to understand the internal implementation details of the aggregated object.

2. You need to provide multiple traversal methods for an aggregated object.

3, in order to traverse different aggregation structure to provide a unified interface, the implementation of the interface for different aggregation structure provides different traversal mode, and the client can be consistent operation of the interface.

To learn more about design patterns, see the Java Design Patterns Learning record-gof design pattern Overview.

Java Design Pattern Learning record-iterator mode

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.