Using the iterator pattern for Java design pattern programming _java

Source: Internet
Author: User

Definition: provides a way to access the elements of a container object without exposing the internal details of that object.
Type: behavior class pattern
class Diagram:

If you want to ask one of the most used patterns in Java, the answer is not a single pattern, not a factory pattern, not a policy model, but an iterator pattern, first of all, to see a piece of code:

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 of the iterator pattern
abstract containers: 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. Remove the current object's method remove (),
Iterator implementation: Implement the method defined in the iterator interface to complete the iteration of the collection.

examples

As the iterator pattern itself is loosely defined, there are a variety of specific implementations. Let's just cite one example here, and we can't render the implementation one by one at all. So for example, let's first enumerate the implementation of the lower iterator pattern.

1. The iterator role defines the traversal interface, but does not specify who will control the iteration. In the Java collection application, it is the client program that controls the traversal process, called an external iterator, and one way to implement this is to control the iteration by itself, called an internal iterator. External iterators are more flexible and powerful than internal iterators, and internal iterators are weak in the Java language environment.

2. There is no rule in the iterator pattern for who to implement the traversal algorithm. It seems logical to implement in the iterator role. Because it facilitates the use of different traversal algorithms on one container, it is also convenient to apply a traversal algorithm to different containers. But this destroys the encapsulation of the container--the container role exposes its own private properties, and in Java it means exposing its own private properties to other classes.

So let's put it in the container role to make it happen. The iterator role is then elevated to simply hold a function that traverses the current position. But the traversal algorithm is tightly bound to a particular container.

In the Java collection application, the specific iterator role provided is the internal class defined in the container role. This protects the encapsulation of the container. But at the same time the container also provides a traversal algorithm interface, you can extend your own iterator.

OK, let's look at how the iterator in the Java collection is implemented.

The iterator role simply defines the traversal interface public interface Iterator {Boolean hasnext ();
 Object next ();
void Remove (); }//Container role, here take list for example. It is also just an interface, do not list out the//specific container role, is the realization of the list interface ArrayList class. In order to highlight the focus here refers to the list and iterator related content//specific iterator role, it is in the form of internal classes.

Abstractlist is for the purpose of extracting the common parts of individual container roles.  Public abstract class Abstractlist extends Abstractcollection implements List {...//This is the factory method that is responsible for creating the specific iterator role public iterator

Iterator () {return new Itr ();}
 The specific iterator role as an internal class Itr implements iterator {int cursor = 0;
 int lastret =-1;

 int expectedmodcount = Modcount;
 public Boolean Hasnext () {return cursor!= size ();
  Public Object Next () {checkforcomodification ();
   try {Object next = get (cursor);
   Lastret = cursor++;
  return to Next;
   catch (Indexoutofboundsexception e) {checkforcomodification ();
  throw new Nosuchelementexception ();
   } public void Remove () {if (Lastret = 1) throw new IllegalStateException ();

  Checkforcomodification (); try {AbstractList.this.remove (lastrET);
   if (Lastret < cursor) cursor--;
   Lastret =-1;
  Expectedmodcount = Modcount;
  catch (Indexoutofboundsexception e) {throw new concurrentmodificationexception (); } final void Checkforcomodification () {if (Modcount!= expectedmodcount) throw new concurrentmodificationexcept
 Ion ();

 }
}

As for the use of iterator patterns. As listed in the introduction, the client program first obtains the specific container role and then obtains the specific iterator role through the specific container role. This allows you to use the specific iterator role to traverse the container ...


advantages and disadvantages of the iterator pattern
the advantages of an iterator pattern are:
Simplifies the traversal method, for the traversal of the object set, it is still troublesome, for the array or the sequence table, we can still get through the cursor, but the user needs to understand the set of the premise of a very clear, but for the hash table, the user traversal is more cumbersome. With the introduction of the iterator method, users are much simpler to use.
can provide a variety of traversal methods, such as the sequence table, we can provide positive sequence traversal, reverse traversal of two iterators, the user only need to get our implementation of a good iterator, you can easily traverse the collection.
The encapsulation is good, the 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.

the scenario for the iterator pattern
The iterator pattern is symbiotic with the set, in general, as long as we implement a set, we need to provide an iterator for the set, like Collection,list, set, map, and so on in Java, which have their own iterators. If we were to implement a new container like this, we would certainly need to introduce an iterator pattern to implement an iterator for our container.
However, because the container is too closely related to the iterator, so most languages provide iterators when implementing containers, and the containers and iterators provided by these languages can meet our needs in the vast majority of situations, so the scenario that requires us to practice the iterator pattern now is relatively rare, All we need to do is use the existing containers and iterators in the language.

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.