6. Iterator mode

Provide a way to access various elements in a container object without exposing the internal details of the object.

Class Diagram

 

 

Code example

If you want to ask one of the most used patterns 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:

1.	public static void print(Collection coll){  
2.	    Iterator it = coll.iterator();  
3.	    while(it.hasNext()){  
4.	        String str = (String)it.next();  
5.	   

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

1.	interface Iterator {  
2.	    public Object next();  
3.	    public boolean hasNext();  
4.	}  
5.	class ConcreteIterator implements Iterator{  
6.	    private List list = new ArrayList();  
7.	    private int cursor =0;  
8.	    public ConcreteIterator(List list){  
9.	        this.list = list;  
10.	    }  
11.	    public boolean hasNext() {  
12.	        if(cursor==list.size()){  
13.	            return false;  
14.	        }  
15.	        return true;  
16.	    }  
17.	    public Object next() {  
18.	        Object obj = null;  
19.	        if(this.hasNext()){  
20.	            obj = this.list.get(cursor++);  
21.	        }  
22.	        return obj;  
23.	    }  
24.	}  
25.	interface Aggregate {  
26.	    public void add(Object obj);  
27.	    public void remove(Object obj);  
28.	    public Iterator iterator();  
29.	}  
30.	class ConcreteAggregate implements Aggregate {  
31.	    private List list = new ArrayList();  
32.	    public void add(Object obj) {  
33.	        list.add(obj);  
34.	    }  
35.	  
36.	    public Iterator iterator() {  
37.	        return new ConcreteIterator(list);  
38.	    }  
39.	  
40.	    public void remove(Object obj) {  
41.	        list.remove(obj);  
42.	    }  
43.	}  
44.	public class Client {  
45.	    public static void main(String[] args){  
46.	        Aggregate ag = new ConcreteAggregate();  
47.	        ag.add("小明");  
48.	        ag.add("小红");  
49.	        ag.add("小刚");  
50.	        Iterator it = ag.iterator();  
51.	        while(it.hasNext()){  
52.	            String str = (String)it.next();  
53.	            System.out.println(str);  
54.	        }  
55.	    }  
56.	} 

In the above code, Aggregate is the container class interface. You can imagine Collection, List, Set, etc. Aggregate is their simplified version. There are three main methods in the container class interface: add object method add, delete object method remove, and obtain iteration器method iterator. Iterator is an iterator interface. There are two main methods: get the iteration object method next, and determine whether the iteration is completed hasNext. You can compare the two interfaces java.util.List and java.util.Iterator to think for yourself.

The structure of the iterator pattern

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

Advantages and disadvantages of the iterator pattern

  The advantages of the iterator pattern are:

  1. The traversal method is simplified. It is still more troublesome to traverse the collection of objects. For arrays or ordered lists, we can still get them through cursors, but users need to traverse objects by themselves on the premise of having a clear understanding of the collection. For the hash table, it is more troublesome for users to traverse. After the iterator method is introduced, it is much simpler for users to use.
  2. A variety of traversal methods can be provided. For example, for an ordered list, we can provide two iterators as needed, forward traversal and reverse traversal. Users only need to get the iterator that we have implemented to easily perform collections Traversed.
  3. Good encapsulation, users only need to get the iterator to traverse, but don’t care about the traversal algorithm.

 Disadvantages of the iterator pattern:

  1. For relatively simple traversals (like arrays or ordered lists), using iterators to traverse is more cumbersome, and everyone may feel that, like ArrayList, we would rather use for loops and get methods to traverse the collection.

Applicable scenarios of iterator mode

The iterator pattern coexists and dies 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. These collections have their own The iterator. If we want to implement such a new container, of course, we also need to introduce the iterator mode to implement an iterator for our container.

       However, because the relationship between containers and iterators is too close, 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 mode by ourselves. We only need to use the existing containers and iterators in the language.

 

 

 

Guess you like

Origin blog.csdn.net/sinat_37138973/article/details/88178144