The iterator pattern for Java design mode (ii)

Source: Internet
Author: User

The source code is JDK1.8 as reference

1. Definition:
Iterator provides a way to access individual elements in a container object without exposing the object's internal details.

2. Analysis:
General class Diagram:

class Diagram parsing:
2.1.Iterator Abstract Iterator
Abstract iterators are responsible for defining common interface conventions, which are basically based on the definition of the iterator interface in the JDK, the source code is as follows:

public      Interface  iterator<e> {boolean hasnext ();    E next (); default  void  Remove () {throw  new  unsupportedoperationexception (); } /* * @since 1.8 */ default  void  foreachremaining (consumer<? Super E> Action) {Objects.requirenonnull (action); while     (Hasnext ()) action.accept (Next ()); }}

The basic iterator will have the constraints defined by the Hasnext (), Next () two methods, which provide a way to delete the inner elements of the container during the time elapsed and add the default method foreachremaining in JDK1.8 ( Consumer action), allowing you to specify an action to traverse when traversing.
2.2.Concrete iterator specific iterator
Concrete iterator implements the iterator interface, realizes its internal method definition, completes the concrete iteration, at this time the iterator can realize in two ways.
One is that Concreteiterator holds a reference to a collection of specific containers, iterating through the elements of the collection, and the general iterator is implemented in this way.
One is that concreteiterator is used as the inner class of the container collection, because of the particularity of the inner class, the concrete implementation of the external class can be obtained at any time, and the iterative operation is completed, but the iterator of this kind of implementation is dependent and cannot be reused.
2.3.Aggregate Abstract Container
Aggregate abstract container is an optional presence in iterator mode, which defines some of the upper-level operations of the container in order to deal with the correlation between multiple containers.
2.4.Concrete Aggregate Concrete container
The implementation of the specific container, need to define its internal structure, such as ArrayList dependent array complete element access, HashMap dependent array, linked list to complete the access of elements.

3. Specific application:
Described above is a general approach to iterator design patterns, followed by a simple example based on its common definition, traversing through the iterator pattern.
3.1.Iterator Abstract Iterator
This iterator convention uses the definition of java.util.Iterator.
3.2.Concrete iterator specific iterator

 Public  class concreteiterator implements Iterator {    PrivateVector vector =NewVector ();//: Define the current cursor     Public intcursor =0;@SuppressWarnings("Unchecked") Public Concreteiterator(Vector _vector) { This. vector = _vector; }//: Determine if the tail is reached     Public Boolean Hasnext() {if( This. cursor = = This. Vector.size ()) {return false; }Else{return true; }    }//: Returns the next element     PublicObjectNext() {Object result =NULL;if( This. Hasnext ()) {result = This. Vector.get ( This. cursor++); }Else{result =NULL; }returnResult }//: Delete Current element     Public Boolean Remove() { This. Vector.remove ( This. cursor);return true; }}

3.3.Aggregate Abstract Container

publicinterface Aggregate {    // .. 是容器必然有元素的增加    publicvoidaddobject);    // .. 减少元素    publicvoidremoveobject);    // .. 由迭代器来遍历所有的元素    publiciterator();}

3.4.Concrete Aggregate Concrete Container

 Public  class concreteaggregate implements Aggregate {    //: Container that holds objects    PrivateVector vector =NewVector ();//: Add an element     Public void Add(Object object) { This. Vector.add (object); }//: Returns an Iterator object     PublicIteratoriterator() {return NewConcreteiterator ( This. Vector); }//: Delete an element     Public void Remove(Object object) { This. Remove (object); }}

In the example, the Concreteaggregate container uses vectors internally as a struct, and the following code can be used:

publicclass Test{    publicstaticvoidmain(String[] args){        new ConcreteAggregate();        Iterator it = ca.iterator();        while(it.hashNext()){            it.next();        }    }}

4.forEachRemaining Applications:
Foreachremaining is the default method of the interface added in JDK1.8, which embodies the idea of functional programming in JDK1.8.
4.1. First implement the consumer interface

class Action implements Consumer{    @Override    publicvoid accept(Object o) {        // .. 自己需要处理的事情    }}

4.2. Iterating using a iterator instance

new ConcreteAggregate();Iterator it = ca.iterator();it.forEachRemaining(new Action());

Note: The above is a functional approach provided by JDK1.8, which cannot be done in a lower version of the JDK.
5. Note:
1. Although the iterator model is a very common pattern, the general container has already provided its implementation, and unless you define and implement the container yourself, iterator is not necessary, and it is also important to note that in many JDK container implementations,
For a container class that implements the iterator interface, some implementations are only additional functions, such as container classes arraylist, vectors, etc. based on simple array implementations, whose iterators are slower than for loops, while for some container classes based on linked list implementations
LinkedList, and so on, its iterators faster than for-loop speed, so in the application, the need for specific considerations.
2. For the newly added for (:) Fast iterations in JDK1.7, formally based on iterator, only the iterator interface is implemented and the collection container with the corresponding iterator can be used for processing.
3. The most reason to use the iterator design pattern is because the iterator can be separated from the implementation and incremented separately.
4. Over-reliance on specific classes can increase the coupling between classes and classes, and increase the difficulty of component reuse. Abstract classes and interfaces must be introduced in order to reduce the coupling and to reuse the class as part.

Note: I am referring to the "design mode of Zen" and "design mode" two books learned, which added their own understanding of iterator design patterns, as well as the JDK in the source code understanding.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The iterator pattern for Java design mode (ii)

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.