1024programmer Java Using the iterator pattern for Java design pattern programming

Using the iterator pattern for Java design pattern programming

Definition: Provides a way to access individual elements in a container object without exposing the object’s internal details.
Type: Behavioral Pattern
Class diagram:

2016217103153704.jpg (542×287)

If you want to ask about the most commonly used pattern in Java, the answer is not the singleton pattern, nor the factory pattern, nor the strategy pattern, but the iterator pattern. Let’s look at a piece of code first:

 public static void print(Collection coll){
   Iterator it = coll.iterator();
   while(it.hasNext()){
     String str = (String)it.next();
     System.out.println(str);
   }
 }
 

The function of this method is to print a collection of strings in a loop, in which the iterator mode is used. The Java language has completely implemented the iterator mode. Iterator is translated into Chinese as iterator. When it comes to iterators, first of all, it is related to collections. Collections are also called collections, containers, etc. We can think of collections as containers that can contain objects, such as List, Set, Map, and even arrays can be called collections. The function of an iterator is to traverse the objects in the container one by one.

Structure of the iterator pattern
Abstract container: Generally an interface that provides an iterator() method, such as Collection interface, List interface, Set interface, etc. in java.
Concrete container: It is a concrete implementation class of an abstract container, such as the ordered list of the List interface that implements ArrayList, the linked list of the List interface that implements LinkList, the hash list of the Set interface that implements HashSet, etc.
Abstract iterator: defines the methods needed to traverse elements. Generally speaking, there are three methods: first() to get the first element, next() to get the next element, and isDone to determine whether the traversal is over. () (or hasNext()), method to remove the current object remove(),
Iterator implementation: implement the methods defined in the iterator interface to complete the iteration of the collection.

Example

Since the iterator pattern itself is relatively loosely regulated, the specific implementations vary. We only give one example here and cannot present all implementation methods at all. Therefore, before giving an example, let us first enumerate the implementation of the iterator pattern.

1. The iterator role defines the interface for traversal, but does not specify who controls the iteration. In the application of Java collection, the client program controls the traversal process, which is called an external iterator; another implementation method is to control the iteration by the iterator itself, which is called an internal iterator. External iterators are more flexible and powerful than internal iterators, and internal iterators have very weak usability in the Java language environment.

2. There is no stipulation on who implements the traversal algorithm in the iterator pattern. It seems natural to implement it in the iterator role. Because it is convenient to use different traversal algorithms on one container, and it is also convenient to apply one traversal algorithm to different containers. But this destroys the encapsulation of the container – the container role must expose its own private properties, which in Java means exposing its own private properties to other classes.

Then let’s put it into the container role to implement it. In this way, the role of the iterator is reduced to merely storing a function for traversing the current position. But the traversal algorithm is tightly tied to a specific container.

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

Okay, let’s take a look at how iterators in Java Collection are implemented.

 //The iterator role only defines the traversal interface

 public interface Iterator {
 boolean hasNext();
 Object next();
 void remove();
 }

 //Container role, here we take List as an example.  It is just an interface, so I won’t list it here.
 //The specific container role is ArrayList and other classes that implement the List interface.  In order to highlight the key points, here is a list of content related to iterators.
 //The specific iterator role is in the form of an inner class.  AbstractList exists to extract the common parts of each specific container role.

 public abstract class AbstractList extends AbstractCollection implements List {
 …
 //This is the factory method responsible for creating specific iterator roles
 public Iterator iterator() {
 return new Itr();
 }

 //Specific iterator role as inner class

 private 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 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 checkForCommodification() {
 ​if (modCount != expectedModCount)
 ​throw new ConcurrentModificationException();
 }
 }

 

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

Advantages and Disadvantages of Iterator Pattern
The advantages of the iterator pattern are:
It simplifies the traversal method. It is still troublesome to traverse object collections. For arrays or ordered lists, we can still obtain them through cursors, but users need to traverse objects by themselves under the premise of a clear understanding of the collection. But for For hash tables, it is more troublesome for users to traverse them. After the introduction of the iterator method, it becomes much simpler for users to use it.
It can provide a variety of traversal methods. For example, for ordered lists, we can provide forward-order traversal and reverse-order traversal iterators as needed. To use it, users only need to get the iterators we have implemented, and then they can conveniently perform operations on the collection. Traversed.
The encapsulation is good, the user only needs to get the iterator to traverse, and does not need to care about the traversal algorithm.
​​​​ Disadvantages of the iterator pattern:
For relatively simple traversals (like arrays or ordered lists), it is more cumbersome to use iterators to traverse. You may all feel that, like ArrayList, we would rather use for loops and get methods to traverse collections.

Applicable scenarios of the iterator pattern
      The iterator pattern is symbiotic with collections. Generally speaking, as long as we implement a collection, we need to provide iterators for this collection at the same time, just like Collection, List, Set, Map, etc. in Java. Collections have their own iterators. If we want to implement such a new container, of course we also need to introduce the iterator pattern and implement an iterator for our container.
However, because containers are so closely related to iterators, most languages ​​provide iterators when implementing containers, and the containers and iterators provided by these languages ​​can meet our needs in most cases. , so it is still relatively rare that we need to practice the iterator pattern ourselves. We only need to use the existing containers and iterators in the language.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/703496

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索