One, iterator (Iterator) mode
Iterators are made for collection objects, which inevitably involve the addition and deletion of collection elements, and certainly support the operation of iterating over the collection elements, and we can put the traversal in the collection object at this point, but then the collection object takes too much responsibility. One of the principles of object-oriented design is a single principle of responsibility, so we need to separate these responsibilities as much as possible and use different classes to take on different responsibilities. The iterator pattern is the responsibility of iterating through the elements of the collection with an iterator class.
The iterator pattern provides a way to sequentially access individual elements in an aggregated object (understood as a collection object) without exposing the object's internal representation, so that the internal structure of the collection is not exposed and external code transparently accesses the data inside the collection.
Second, the structure of the iterator pattern
Since the iterator pattern assumes responsibility for iterating over the collection object, the pattern naturally exists in 2 classes, one aggregation class and one iterator class. One of the object-oriented principles is programming for the interface, so in the iterator pattern, the 2 interfaces are abstracted, one is the aggregation interface and the other is the iterator interface, so that the iterator pattern has four roles, the specific class diagram is as follows:
As you can see, the iterator pattern consists of the following roles:
- iterator Role (Iterator): The iterator role is responsible for defining interfaces that access and traverse elements
- specific iterator role (concrete iteraror): The specific iterator role implements the iterator interface and needs to record the current position in the traversal.
- aggregation Role (Aggregate): The aggregation role is responsible for defining the interface that gets the iterator role
- Specific aggregation roles (concrete Aggregate): aggregate role implementation aggregation role interfaces.
Three, the implementation of the iterator pattern
//Abstract Aggregation ClassesusingSystem; Public Interfaceilistcollection{Iterator getiterator ();}//iterator abstract class Public Interfaceiterator{BOOLMoveNext (); Object GetCurrent (); voidNext (); voidReset ();}//Specific aggregation classes Public classconcretelist:ilistcollection{ReadOnly int[] _collection; Publicconcretelist () {_collection=New int[] {2,4,6,8 }; } PublicIterator Getiterator () {return NewConcreteiterator ( This); } Public intLength {Get{return_collection. Length; } } Public intGetElement (intindex) { return_collection[index]; }}//Specific iterator Classes Public classconcreteiterator:iterator{//iterators need to refer to a collection object for traversal operations. Private ReadOnlyconcretelist _list; Private int_index; Publicconcreteiterator (concretelist list) {_list=list; _index=0; } Public BOOLMoveNext () {if(_index <_list. Length) {return true; } return false; } PublicObject GetCurrent () {return_list. GetElement (_index); } Public voidReset () {_index=0; } Public voidNext () {if(_index <_list. Length) {_index++; } }}//Clientclassprogram{Static voidMain (string[] args) {ilistcollection list=Newconcretelist (); Iterator Iterator=list. Getiterator (); while(iterator. MoveNext ()) {vari = (int) iterator. GetCurrent (); Console.WriteLine (i.ToString ()); Iterator. Next (); } console.read (); }}
Naturally, the result of the above code is also the output of each element of the collection, and the result is as follows:
2468
Four. The application of the iterator pattern in net
In. NET, the aggregation interface and iterator interfaces in the iterator pattern already exist, where the IEnumerator interface acts as an iterator role, and the Ienumberable interface acts as an abstract clustered role, with only one GetEnumerator () method, You can refer to MSDN for your own definition of these two interfaces. In. NET 1.0, many of the collections in the. NET class library have implemented the iterator pattern, You can use the Anti-compilation tool reflector to see under the mscorlib assembly under the System.Collections namespace of the class, here gives the ArrayList definition code, the implementation code can self-use the anti-compilation tool to view, the specific code is as follows:
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic; Public classarraylist:ilist, ICollection, IEnumerable, icloneable{// Fields Private Const intDefaultcapacity =4; Private Object[] _items; Private int_size; [NonSerialized]Private Object_syncroot; Private int_version; PublicArrayList (Object[] Items,intSizeObjectSyncRoot,intversion) {_items=items; _size=size; _syncroot=SyncRoot; _version=version; } Public VirtualIEnumerator GetEnumerator (); Public VirtualIenumerator<> GetEnumerator (intIndexintcount); //Properties Public Virtual intcapacity {Get;Set; } Public Virtual intCount {Get; } ..............//For more code, please use the Anti-compilation tool reflector to view}
By looking at the source code you can see that the implementation of the iterator in ArrayList is very similar to the example code we gave earlier. However, in. NET 2.0, the implementation of the iterator pattern is simpler because of the yield return keyword.
V. Application scenarios for the iterator pattern
You might consider using the iterator pattern in the following scenarios:
- The system needs to access the contents of an aggregated object without exposing its internal representation.
- The system needs to support multiple traversal of aggregated objects.
- The system needs to provide a unified interface for different aggregation structures.
Vi. advantages and disadvantages of the iterator pattern
Advantages:
- The iterator pattern allows access to the contents of an aggregated object without exposing its internal representation, which is an iterative abstraction.
- The iterator pattern provides a unified interface for traversing different collection structures, enabling the same algorithm to operate on different sets of structures
Disadvantages:
- An iterator pattern that changes the collection structure in which iterators are traversed causes an exception to occur. So using a foreach statement can only iterate over the collection and not change the elements in the collection while traversing.
Vii. Summary
Here, the content of this blog is the end, the iterator pattern is to abstract an iterator class to separate the collection object traversal behavior, so as not to expose the internal structure of the collection, but also allow external code to transparently access the data inside the collection.
C # design Pattern-iterator mode