JAVA design mode-iterator mode (iterator) __java

Source: Internet
Author: User

Definition: provides a way to access each element of an aggregation object sequentially without exposing the internal details of the object.

Type: object behavior pattern

class Diagram:

If you want to ask one of the most used patterns in Java, the answer is not in single mode, not in Factory mode, not in policy mode, but in iterator mode, first look at a piece of code: [Java] view plain copy public static void print (Collection Coll)       {Iterator it = coll.iterator ();           while (It.hasnext ()) {String str = (String) it.next ();       System.out.println (str); }   }

The purpose of this method is to cycle through a collection of strings, where the iterator pattern is used, the Java language has fully implemented the iterator pattern, and iterator translation into Chinese is the meaning of the iterator. Referring to iterators, first, it is related to the set, the set is also called aggregation, container, etc., we can think of the set as a container that can contain objects, such as List,set,map, and even arrays can be called sets, and the role of iterators is to take the objects in the container one by one.

Structure Abstraction container for an iterator pattern : Typically an interface that provides a iterator () method, such as a collection interface in Java, a list interface, a set interface, and so on. Concrete container: Is the concrete implementation class of the abstract container, for example, the list interface is ordered to realize the realization of the hash list of the Linklist,set interface of the Arraylist,list interface HashSet etc. Abstract iterator: Defines the methods needed to traverse an element, typically there are three methods: the first () method is taken, the next element is obtained by the method next (), and the Method Isdone () (or Hasnext ()) is determined to determine whether or not to traverse the end. Removes the current object's method remove (), the iterator implements: implements the method defined in the iterator interface, completes the collection iteration.

Code Implementation

Iterator interface Iterator {public Object next ();
public boolean hasnext (); }//Specific iterator class Concreteiterator implements iterator {private List = new ArrayList ()///iterator internal collection private int curs

	or = 0;
	Public concreteiterator (List list) {this.list = list;
		public Boolean Hasnext () {if (cursor = = List.size ()) {return false;
	return true;
		Public Object Next () {object obj = null;
		if (This.hasnext ()) {obj = This.list.get (cursor++);
	return obj;

	}///Aggregation Interface interface Aggregate {public void Add (Object obj);

	public void Remove (Object obj);	Public iterator iterator (); 

	Returns an appropriate instance of Concreteiterator}//Concrete aggregation class Concreteaggregate implements Aggregate {Private list = new ArrayList ();
	public void Add (Object obj) {list.add (obj);
	Public iterator iterator () {return new concreteiterator (list);
	public void Remove (Object obj) {list.remove (obj); } public class Iteratorpatterndemo {/** * @param args/public STAtic void Main (string[] args) {Aggregate ag = new concreteaggregate ();  
        Ag.add ("AA");  
        Ag.add ("BB");  
        Ag.add ("CC");  
        Ag.add ("DD");  
        Iterator it = Ag.iterator ();  
            while (It.hasnext ()) {String str = (String) it.next ();  
        System.out.println (str); }  
	}
}


The above code, aggregate is a container class interface, you can imagine Collection,list,set, aggregate is their simplified version, the container class interface has three main methods: Add Object method Add, Delete object method Remove, Gets the iterator method iterator. Iterator is an iterator interface, there are two methods: to get the Iterative object method next, to determine whether the iterative completion method Hasnext, you can compare java.util.List and java.util.Iterator two interfaces to think for themselves.


The iterator pattern has three important roles:

It supports traversing a complex aggregation of aggregations in different ways, and can be traversed in many ways. For example, the map iterator simplifies the aggregation of interfaces with an iterator traversal interface, and the aggregation itself no longer requires a similar traversal interface. This simplifies the aggregation of interfaces. There can be multiple traversal of each iterator on the same aggregation to keep its own iterative state. So you can do multiple traversal at the same time.


advantages and disadvantages of the iterator pattern

The advantages of an iterator pattern are:

Simplifies traversal of a collection of objects, still more troublesome, for arrays or sequential tables, we can still get through the cursor, but the user needs to understand the set on the premise of the very clear, but for the hash table, the user traversal is more troublesome. With the introduction of the iterator method, users are much simpler to use.
can provide a variety of traversal methods for example, for a sequence table, we can provide positive sequence traversal, reverse traversal of two iterators, users only need to get our implementation of a good iterator, we can easily traverse the collection.
The encapsulation good user only needs to get the iterator to be able to traverse, but for the traversal algorithm does not need to care.


Disadvantages of the iterator pattern:

For a simpler traversal (like an array or a sequence table), it's tedious to iterate using an iterator, and you might have a feeling, like ArrayList, that we'd rather use the for loop and get methods to traverse the collection.

Applicable Scenarios

Accesses the contents of an aggregated object without exposing its internal representation. Supports multiple traversal of aggregated objects. Provides a unified interface for traversing multiple different aggregation structures (i.e., support for polymorphic iterations).


Summarize

The key idea of the iterator pattern is to separate the access and traversal of the list from the list object and put it into an iterator (iterator) object. The iterator class defines an interface that accesses the element of the list . The iterator object is responsible for tracking the current element, that is, it knows which elements have been traversed.



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.