C # Design Pattern (16)--Iterator mode (Iterator pattern)

Source: Internet
Author: User

Original: C # design pattern (16)--Iterator mode (Iterator pattern)

First, Introduction

In my previous blog post, I shared my understanding of the command pattern, which was mainly to abstract the behavior into commands, which resulted in low coupling between the requester's behavior and the recipient's behavior. In one chapter, you'll look at the iterator pattern. The following nonsense not much to say, directly into the topic of this blog post.

Ii. Introduction to the iterator pattern

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.

2.1 Definition of the iterator pattern

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.

2.2 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.
2.3 Implementation of the iterator pattern

After introducing the iterator pattern, the following is a concrete look at the implementation of the iterator pattern, the implementation code is as follows:

1  //Abstract Aggregation Classes2      Public Interfaceilistcollection3     {4 Iterator getiterator ();5     }6 7     //iterator abstract class8      Public InterfaceIterator9     {Ten         BOOLMoveNext (); One Object getcurrent (); A         voidNext (); -         voidReset (); -     } the  -     //Specific aggregation classes -      Public classconcretelist:ilistcollection -     { +         int[] collection; -          Publicconcretelist () +         { ACollection =New int[] {2,4,6,8 }; at         } -  -          PublicIterator getiterator () -         { -             return NewConcreteiterator ( This); -         } in  -          Public intLength to         { +             Get{returncollection. Length; } -         } the  *          Public intGetElement (intindex) $         {Panax Notoginseng             returnCollection[index]; -         } the     } +  A     //Specific iterator Classes the      Public classConcreteiterator:iterator +     { -         //iterators need to refer to a collection object for traversal operations. $         Privateconcretelist _list; $         Private int_index; -  -          Publicconcreteiterator (concretelist list) the         { -_list =list;Wuyi_index =0; the         } -  Wu  -          Public BOOLMoveNext () About         { $             if(_index <_list. Length) -             { -                 return true; -             } A             return false; +         } the  -          PublicObject getcurrent () $         { the             return_list. GetElement (_index); the         } the  the          Public voidReset () -         { in_index =0; the         } the  About          Public voidNext () the         { the             if(_index <_list. Length) the             { +_index++; -             } the                 Bayi         } the     } the  -     //Client -     class Program the     { the         Static voidMain (string[] args) the         { the Iterator Iterator; -Ilistcollection list =Newconcretelist (); theiterator =list. Getiterator (); the  the              while(iterator. MoveNext ())94             { the                 inti = (int) iterator. GetCurrent (); the Console.WriteLine (i.ToString ()); the iterator. Next ();98             } About  - Console.read ();101         }102}

Naturally, the result of the above code is also the output of each element of the collection, as shown in the results:

Three. 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:

1  Public classarraylist:ilist, ICollection, IEnumerable, ICloneable2 {3     // Fields4     Private Const int_defaultcapacity =4;5     Private Object[] _items;6     Private int_size;7 [NonSerialized]8     Private Object_syncroot;9     Private int_version;Ten     Private Static ReadOnly Object[] emptyarray; One  A      Public VirtualIEnumerator GetEnumerator(); -      Public VirtualIEnumeratorGetEnumerator(intIndexintcount); -  the     //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, because of the yield return keyword, implementing the iterator pattern is easier, and more about iterators can refer to my blog post.

Iv. 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.
V. Advantages and disadvantages of the iterator pattern

Because iterators assume the responsibility of traversing collections, the following advantages are available:

    • 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

The flaw in the iterator pattern:

    • 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.
Vi. 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. A blog post will introduce you to the Observer pattern.

C # Design Pattern (16)--Iterator mode (Iterator pattern)

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.