It's been said many times. Design Patterns---iterator patterns

Source: Internet
Author: User
Tags abstract new set

[Turn your rational mind slowly into a conditioned reflex]

In this article, we describe the iterator pattern, and the topic structure is the same as above. Practice, let's take a look at the environment of our example project:

Operating system: Win7 x64

Other software: Eclipse MARS,JDK8

--------------------------------------------------------------------------------------------------------------- ---------------------- Classic Questions:

A traversal (iterative) thought analysis of a particular set (aggregation):

Point one: The so-called traversal, is to have all access without exception.

Point two: Traversal (iteration) is only comprehensive, ignoring the order. That is, elements of any location can be used as a starting point. Example Project:


iterator Pattern template code:


Create a Aggregate.java file with the following details:

Package com.csdn.ingo.gof_Iterator;

Import java.util.ArrayList;
Import java.util.List;

Public abstract class Aggregate {
	protected list<object> objects = new arraylist<object> ();
	Public Aggregate (List objects) {
		this.objects = objects;
	}
	public void Add (Object obj) {
		this.objects.add (obj);
	}
	public void Remove (Object obj) {
		this.objects.remove (obj);
	}
	Public List getobjects () {
		return this.objects;
	}
	
	Public abstract Iterator Createiterator ();
}
Create a Concreteaggregate.java file with the following details:

Package com.csdn.ingo.gof_Iterator;

Import java.util.ArrayList;
Import java.util.List;

public class Concreteaggregate extends Aggregate {public
	concreteaggregate (List objects) {
		Super (objects);
		TODO auto-generated constructor stub
	}
	private list<object> items = new arraylist<object> ();
	public int Count;
	@Override public
	Iterator createiterator () {
		return to new Concreteiterator (this);
	}
	public int GetCount () {
		return items.size ();
	}
	public void SetCount (int count) {
		count = count;
	}
}
Create a Concreteiterator.java file with the following details:

Package com.csdn.ingo.gof_Iterator;

Import java.util.List;

public class Concreteiterator extends Iterator {
	private concreteaggregate aggregate;
	Private List aggregates;
	private int cursor1;
	private int cursor2;
			
	Public Concreteiterator (concreteaggregate aggregate) {
		this.aggregate = aggregate;
		This.aggregates = Aggregate.getobjects ();
		Cursor1 = 0;
		Cursor2 = Aggregates.size ()-1;
	}

	@Override Public
	Boolean IsFirst () {
		return (cursor2==-1);
	}
	@Override public
	Void Previous () {
		if (cursor2>-1) {
			cursor2--;
		}
	}
	@Override Public
	Boolean islast () {
		return (cursor1==aggregates.size ());
	}
	@Override public
	Object Getcurrentitem () {
		return aggregates.get (Cursor1);
	}
	@Override public
	Object Getpreviousitem () {
		return aggregates.get (CURSOR2);
	}

	@Override public
	Void Next () {
		if (cursor1<aggregates.size ()) {
			cursor1++;}}
}
Create a Iterator.java file with the following details:

Package com.csdn.ingo.gof_Iterator;

Public abstract class Iterator 
{public
    abstract Boolean isFirst ();
    public abstract void Next ();
    public abstract void Previous ();
    Public abstract Boolean islast ();
    Public abstract Object Getcurrentitem ();
    Public abstract Object Getpreviousitem ();
}
Create a Window.java file with the following details:

Package com.csdn.ingo.gof_Iterator;

Import java.util.ArrayList;
Import java.util.List;

public class Window {public
	static void Main (string[] args) {
		List products =new ArrayList ();
		Products.add ("AAA");
		Products.add ("BBB");
		Products.add ("CCC");
		Products.add ("DDD");
		Products.add ("EEE");
		
		Iterator Iterator;
		Aggregate list;
		List = new Concreteaggregate (products);
		iterator = List.createiterator ();
		
		SYSTEM.OUT.PRINTLN ("---forward traversal---");
		while (!iterator.islast ()) {
			System.out.println (Iterator.getcurrentitem () + ",");
			Iterator.next ();
		}
		System.out.println ("------------");
		SYSTEM.OUT.PRINTLN ("---reverse traversal---");
		while (!iterator.isfirst ()) {
			System.out.println (Iterator.getpreviousitem () + ",");
			Iterator.previous ();}}}

"It may be difficult to see the above code directly. Give the code to you first crossing is the hope that the code will now run, observe the results. Here we introduce the relevant concepts and principles.

Model Summary: iterator pattern structure diagram:


iterator mode:

Provides a way to sequentially access individual elements in an aggregated object without exposing the object's internal representation. components:

Iterator (Abstract iterator): Defines an interface for accessing and traversing elements, declaring a method for traversing elements.

Concreteiterator (Specific iterator): Implements an abstract iterator, completes the traversal of the aggregation object, and records the current traversed index position through the cursor.

Aggregate (Abstract aggregation Class): Used to store and manage element objects, declaring a Createiterator () method to create an iterator object.

Concreteaggregate (Specific aggregation Class): Implements an abstract aggregation class, returning a specific iterator instance.

Special reminder: The iterator pattern is applied to the design method of the factory method pattern. "Detail reference: http://blog.csdn.net/abcd898989/article/details/52859560" jdk built-in iterator: "The following from other blog and JDK source code"

In Java, the common list and set both inherit or implement the Java.util.Collection interface.

The specific contents of collection are as follows:


We see that in addition to the Add,remove method, the iterator method is provided to return an iterator object. The specific Java aggregation class can return a specific iterator object by implementing the Iterator method.

The content of the abstract iterator interface defined in the JDK is as follows:


The official explanations of the above methods are as follows:



Test code:

Package com.csdn.ingo.gof_Iterator;

Import java.util.ArrayList;
Import java.util.List;

public class Window {public
	static void Main (string[] args) {
		List products =new ArrayList ();
		Products.add ("AAA");
		Products.add ("BBB");
		Products.add ("CCC");
		Products.add ("DDD");
		Products.add ("EEE");
		Java.util.Iterator Iterator = Products.iterator ();
		Iterator.next ();
		Iterator.remove ();
		while (Iterator.hasnext ()) {
			System.out.println (Iterator.next ());}}}

Special reminder: The Remove () method itself has no position to move the cursor. Therefore, after the remove () method is called at the current position, the current position, and so on, is then an "empty" element. If you do not move the cursor position, calling the Remove () method again will throw the following exception:


A description of the JDK's list and iterator implementation, as follows: "The following is from the rest of the blog, details refer to the end of the article"


In the JDK, the actual situation is much more complex than the above figure, in addition to inheriting the iterator () method of the collection interface, the list interface adds a new factory method Listiterator (), which is designed to create an iterator of the listiterator type.


The method is implemented in the subclass LinkedList of list, which can be used to create objects of the specific Listiterator subclass Listitr, as follows:


The Listiterator () method is used to return an object of the specific iterator Listitr type. In the JDK source code, the iterator () method in Abstractlist calls the Listiterator () method, as follows:


By invoking the iterator () method of the LinkedList class, the client can get an iterator object dedicated to traversing the LinkedList. Questions:

Now that you have the iterator () method, why do you provide a listiterator () method? There is no duplication in the functionality of these two methods. Explanation:

Since there are only three methods defined in the iterator interface, only forward traversal can be achieved through these three methods, and sometimes we need to do the reverse traversal of an aggregate object, Therefore, methods such as hasprevious () and previous () for reverse traversal are declared in the Listiterator interface of the JDK, and if the client needs to call both methods to implement the reverse traversal, the iterator () method can no longer be used to create the iterator. Because the iterator object that is created at this point does not have both methods. We can only create an iterator object of type Listiterator by using the following code: Listiterator i = C.listiterator (); Because of this, you have to increase the declaration of the Listiterator () method in the list interface of the JDK. The method can return an iterator of type listiterator, and the Listiterator iterator has more powerful functions. Reflection: Application Scenarios:

A aggregation object needs to be traversed (in multiple ways), and the traversal details are required to be hidden. The traversal object needs to be done, access and control separated. (which can be understood as read-write separation) provides a unified provider for client access, and the structural differences of aggregate objects do not affect client invocation.

Advantages:

The traversal method can be defined in multiple ways, and the implementation of classes by different iterators is accomplished. The client maintains a unified call method. The separation of the access and control of the aggregation object simplifies the design of the aggregation object. The client interfaces to interface programming, which conforms to the "open and close principle".

Disadvantages:

The implementation process of the iterator pattern requires a lot of interface,class support. Adding or deleting an aggregation type requires a new set of iterator implementations. The implementation process may be more complex. Complete iterative function is more complex, in the design, need to fully consider the future requirements scenario, the wrong design implementation process, it is likely to adversely affect performance, security.

--------------------------------------------------------------------------------------------------------------- ----------------------

So far, the design pattern that has been said many times---the end of the iterator pattern


Special Note: The above description of the JDK source code and list structure, may differ from the current JDK8 version. Suggest that you crossing better be able to debug track learning.


Resources:

Book: "Big Talk design mode"

Other Posts: http://blog.csdn.NET/lovelion/article/details/7563445


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.