Java design pattern iterator pattern "Iterator pattern"

Source: Internet
Author: User

I. Overview

Provides a way to access the aggregation object (container container) without exposing the object's internal details.

Second, the application scenario

1> iterates through the elements in the aggregation object without exposing its content representation, separating the access of the aggregated object from the storage of the internal data. This allows you to access aggregate objects without having to know the implementation details inside them.

2> needs to provide multiple traversal implementations for an aggregate object.


Third, UML class diagram


Iv. participants

1>iterator (Abstract iterator): It defines an interface for accessing and traversing elements, declares a method for traversing data elements, such as the first () method used to get the second element, and the next () method for accessing the next element. The Hasnext () method used to determine if there is a next element, which is used to get the CurrentItem () method of the current element, and so on, will implement these methods in the specific iterator.

2>concreteiterator (Specific iterator): it implements the abstract iterator interface, completes the traversal of the aggregation object, and in the specific iterator through the cursor to record the current position in the aggregation object, in the concrete implementation, the cursor is usually a non-negative integer representing the position.

3>aggregate (Abstract aggregation Class): It is used to store and manage element objects, declaring a Createiterator () method to create an iterator object that acts as an abstract iterator factory role.

4>concreteaggregate (Specific aggregation Class): It implements the Createiterator () method declared in an abstract aggregation class that returns a specific iterator Concreteiterator instance that corresponds to that specific aggregation class.


V. Use case Learning

1. Abstract iterator Iterator.java

/** * Custom Iterator interface <br/> * <b> Description:</b> * This does not use the JDK built-in iterator interface java.util.iterator<e> * @author  [email Protected] * */public interface Iterator {    /** points the cursor to the first element  */public Object One ();/** refers to a cursor to the next element  */public Object Next ();/** determines whether the next element */public a  boolean hasnext (),/** returns the current element that the cursor points to  */public Object CurrentItem ();

2, specific iterator Concreteiterator.java

/** * Specific iterator implementation classes <br/> * Access aggregate objects, traverse internal elements of aggregation objects * @author  [email protected] * */public class Concreteiterator Implement s Iterator {//maintains a reference to a specific aggregation object to facilitate access to the data stored in the aggregated object  private Aggregate aggregate;//defines a cursor to record the current access location  private int Cursorindex; Public Concreteiterator (Aggregate Aggregate) {this.aggregate = Aggregate;} @Overridepublic Object First () {cursorindex = 0;        Return Aggregate.getobjects (). get (Cursorindex);} @Overridepublic Object Next () {cursorindex++; if (Hasnext ()) {return aggregate.getobjects (). get (Cursorindex);} return Aggregate.getobjects (). get (0);} @Overridepublic Boolean hasnext () {if (Cursorindex < Aggregate.getobjects (). Size ()) {return true;} return false;} @Overridepublic Object CurrentItem () {return aggregate.getobjects (). get (Cursorindex);}}
3. Abstract Aggregation classAggregate.java

Import Java.util.arraylist;import java.util.list;/** * Abstract Aggregation Object * @author  [email protected] * */public abstract class Ag gregate {/** creates  an iterator that specifically creates what iteration of the iterator is implemented by a specific subclass */public abstract Iterator createiterator ();    Protected list<object> objects = new arraylist<object> ();  Public Aggregate (List objects) {          this.objects = objects,      } public void AddObject (Object obj) {objects.add (obj);} public void DeleteObject (Object obj) {objects.remove (obj);} Public list<object> getobjects () {return objects;}}
4, Specific aggregation classConcreteaggregate.java

Import java.util.list;/** * Specific Aggregation object * @author  [email protected] * */public class Concreteaggregate extends Aggregate {p Ublic concreteaggregate (List objects) {Super (objects);} /** * Provides a factory method to create a concrete iterator instance <br/> * Iterates through the iterator to perform a specific aggregation object <br/> * This separates the data store of the aggregated object and the access to the aggregated object elements./@Overridepublic I Terator Createiterator () {return new concreteiterator (this);}}
5, the Client test class Client.java

Import Java.util.arraylist;import Java.util.list;public class Client {public static void main (string[] args) {list< string> namelist = new arraylist<string> () Namelist.add ("Java"); Namelist.add ("C"); Namelist.add ("C + +");// Instantiates a specific aggregation object and creates the initialization collection data concreteaggregate languageaggregate = new Concreteaggregate (namelist);//Gets the iterator associated with the aggregation object iterator iterator = Languageaggregate.createiterator ();//The internal data of the aggregation object is accessed through an iterator String firstlanguage = (string) iterator.first ();  Accesses an element System.out.println (firstlanguage) of index 1 in the collection of aggregated objects, Boolean hasnext = Iterator.hasnext (); SYSTEM.OUT.PRINTLN ("Whether there is a next element:" + Hasnext); if (hasnext) {String nextlanguage = (string) iterator.next (); System.out.println ("Next element:" + Nextlanguage);}}}
6. Operation Effect

Does Java still have the next element: True the next element: C



vi. Others/extensions

Java JDK built-in iterator:

When it comes to iterator mode, the first association is that we use the most frequent java.util.Iterator interface in Java.

Yes, he's the iterator built into the JDK. Public interfaceiterator<e> an iterator that iterates over the collection.

One of the points that you want to expand here is: Introduction to Subinterface listiterator<e> for interface iterator

This listiterator sub-interface may be less used in our usual code, so what is his function?

Let's take a look at the following two < compare the answers in them >

Iterator API Method:


Listiterator API Method:


From the above two analyses we can see that iterator can only do one-way traversal, while Listiterator can do two-way traversal (forward/backward), and the list can be modified during iteration. Finally, attach a copy as follows:






Java design pattern iterator pattern "Iterator pattern"

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.