C # design pattern-iterator Pattern

Source: Internet
Author: User

1. Introduction to the iterator mode (Brief Introduction)

The iterator Pattern provides a method to access elements in an aggregate object sequentially without exposing or modifying the internal representation of the Set object.

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

2. What to solve)

During software building, the internal structure of collection objects often varies. However, for these collection objects, we hope that external customers can access the object without exposing its internal structure.CodeTransparently access the contained elements, and the "transparent traversal" is also the sameAlgorithmIt is possible to operate on multiple collection objects.

When you need to access a clustering object, and all these objects need to be traversed, you should consider using the iterator mode. When you need to perform aggregation in multiple ways, you can consider using the iterator mode. Here, you don't have to worry about what an array looks like as an object set, array, list, or simple array. The iterator mode will provide you with an aggregate object Traversal method, instead of having to know what type of aggregate objects are being traversed.

Iii. Code:

View code

 Using  System; Using  System. Collections. Generic;  Using  System. text;  Namespace  Iteratepattern {  Public   Class  Guest {  Public   String  Id {  Get  ;  Set  ;} Public   String  Name {  Get  ;  Set  ;}  Public Guest ( String Aid, String  Aname) {ID = Aid; Name = Aname ;}}  Public  Interface  Iaggrate {iiterator getiterator ();}  Public   Class  Concreateaggrate: iaggrate {list < Object > _ Guest = New List < Object > ();  Public  Iiterator getiterator (){  Return   New Concreateiterator (This  );}  Public   Object   This [ Int  Index] {  Get { Return  _ Guest [Index];}  Set  {_ Guest. Add (value );}}  Public   Int  Count (){ Return  _ Guest. Count ;}}  Public   Interface  Iiterator {  Bool  Next ();}  Class  Concreateiterator: iiterator {concreateaggrate _ aggrate;  Int  Currentindex;  Public  Concreateiterator (concreateaggrate aaggrate) {_ aggrate =Aaggrate; currentindex =- 1  ;}  Public   Object  Current {  Get { Return  _ Aggrate [currentindex] ;}}  Public   Bool  Next () {currentindex ++ ;  Return _ Aggrate. Count ()> Currentindex ;}}  Class  Program {  Static   Void Main ( String  [] ARGs) {concreateaggrate aaggrate = New  Concreateaggrate (); aaggrate [  0 ] = New Guest ( "  1 " , "  Hi  "  ); Aaggrate [  1 ] = New Guest ( "  2  " , "  My  "  ); Aaggrate [  2 ] = New Guest ("  3  " , "  Dear  "  ); Aaggrate [  3 ] = New Guest ( "  4  " , "  Iterator  "  ); Aaggrate [ 4 ] = New Guest ( "  5  " , "  Pattern  "  );  //  Concreateiterator aiterator = new concreateiterator (aaggrate ); Concreateiterator aiterator = (Concreateiterator) aaggrate. getiterator ();  While (Aiterator. Next () console. writeline (guest) aiterator. Current). Name );}}} 

 

Iterator Application

The following is the minimum set owned by the iterator. Current is the attribute and can only be get and cannot be set. There are two other methods: movenext is to go to the next element. If there is no element after accessing the last element, false is returned; reset is reset and return to the initial position.

If a container implements the ienumerable interface, it can support our iterative operations. This design pattern has been internalized into an element of the C # language, that is, the foreach keyword. The defined container must first implement the ienumerable interface. The getenumerator method must return a set of ienumerator types.

View code

 Using  System;  Using  System. Collections. Generic;  Using System. text;  Using  System. collections;  Namespace  Iteratepattern {  Public   Class  Guest {  Public   String  Id {  Get  ;  Set  ;}  Public  String  Name {  Get  ;  Set  ;}  Public Guest ( String Aid, String  Aname) {ID = Aid; Name = Aname ;}}  Public   Class Concreateaggrate: ienumerable {list < Object > _ Guest = New List < Object > ();  Public   Object   This [ Int  Index] {  Get { Return  _ Guest [Index];}  Set {_ Guest. Add (value );}}  Public   Int  Count (){  Return  _ Guest. Count ;}  # Region Ienumerable Member Ienumerator ienumerable. getenumerator (){  Return   New Concreateiterator ( This  );}  # Endregion }  Class  Concreateiterator: ienumerator {concreateaggrate _ aggrate;  Int  Currentindex;  Public  Concreateiterator (concreateaggrate aaggrate) {_ aggrate = Aaggrate; currentindex =- 1  ;}  # Region Ienumerator Member Object Ienumerator. Current {  Get { Return  _ Aggrate [currentindex] ;}}  Bool  Ienumerator. movenext () {currentindex ++ ;  Return _ Aggrate. Count ()> Currentindex ;}  Void  Ienumerator. Reset () {currentindex =- 1 ;}  # Endregion  }  Class  Program {  Static   Void Main ( String  [] ARGs) {concreateaggrate aaggrate = New  Concreateaggrate (); aaggrate [  0 ] = New Guest ( " 1  " , "  Hi  "  ); Aaggrate [  1 ] = New Guest ( "  2  " , "  My  "  ); Aaggrate [  2 ] =New Guest ( "  3  " , "  Dear  "  ); Aaggrate [  3 ] = New Guest ( "  4  " , "  Iterator  " ); Aaggrate [  4 ] = New Guest ( "  5  " , "  Pattern  "  );  Foreach (Guest aguest In  Aaggrate) console. writeline (aguest. Name );}}} 

 

Working Mechanism of foreach

Ienumerator ietor =Aaggrate. getenumerator ();While(Ietor. movenext () {guest aguest=(Guest) ietor. Current; console. writeline (aguest );}

 

 

Traverse all the interfaces accessed in the Code, without worrying about the internal structure of the set. The above code is equivalent to the following foreach.

Structure)

 

Key points of the iterator Mode

Iterative Abstraction: access the content of an aggregate object without exposing its internal representation. Iterative polymorphism: provides a unified interface for Traversing different set structures, so that the same algorithm can be operated on different set structures. For example, suppose we have a summation algorithm.

It can operate on multiple sets that support iterators. If you write this algorithm into arraylist, it will be very limited. At the same time, we can use the C # foreach statement to write.

Our algorithms should be independent, and we should try our best to operate interfaces when writing, so that we can write an algorithm to cope with the changes in N sets, this allows the same algorithm to operate on different sets. Robustness of the iterator: Changing the collection structure of the iterator while traversing will cause problems. That is to say, during iteration, we should only perform read operations and cannot change the container interface. For example, it is impossible to delete an element during traversal. The constructor of the container cannot touch it. Once the structure is changed, traversal will fail.

The following changes to I will not affect the original array content, because I is of the int type and it is only a copy.

We must provide users with read-only iterations as much as possible. Ensure that each element is traversed only once.

(From: Mountain Day animal blog Park, http://www.cnblogs.com/cdts_change/archive/2010/10/17/1853689.html)

Conclusion)

From the above examples, we can see that although we do not show the reference iterator, it is actually traversed by the iterator. In general, the iterator mode separates the iteration behavior of the set object and abstracts an iterator class to take charge of it. In this way, the internal structure of the set can be not exposed, in addition, external code can transparently access the elements inside the set.

The iterator mode is widely used to access data such as arrays, sets, and lists, especially database data operations, therefore, various advanced languages have encapsulated him. Instead, they feel that this mode is not very common.

 

Reprinted please indicate the source: edward_jie, http://www.cnblogs.com/promise-7/archive/2012/05/28/2521918.html

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.