C # design Pattern (16) -- Iterator Pattern)

Source: Internet
Author: User
Tags reflector

C # design Pattern (16) -- Iterator Pattern)
I. Introduction I shared my understanding of the command mode in the previous blog. The command mode mainly abstracts the behavior into commands, making the behavior of the requester and the behavior of the receiver form a low coupling. In this chapter, we will introduce the iterator mode. I will not talk about the following nonsense. I will go directly to the topic of this blog post. II. Introduction to the iterator mode the iterator is generated for the set object. For the set object, the addition and deletion operations of the Set element are required, at the same time, it certainly supports the traversal of set elements. We can also put the traversal operation in the Set object at this time, but in this way, the set object will assume too many responsibilities, one of the principles of object-oriented design is the single responsibility principle. Therefore, we should try our best to separate these responsibilities and use different classes to assume different responsibilities. The iterator mode uses the iterator class to traverse the set elements. 2.1 Definition of the iterator pattern the iterator Pattern provides a method to access each element of an aggregate object in sequence (understood as a collection object) without exposing the internal representation of the object, in this way, the internal structure of the set is not exposed, and external code can transparently access the data in the set. 2.2 The structure of the iterator mode since the iterator mode assumes the responsibility of traversing the set object, there are two classes in this mode, one is the aggregation class and the other is the iterator class. In the object-oriented principles, there is also an interface-oriented programming. Therefore, in the iterator mode, two interfaces are abstracted, one is an aggregate interface and the other is an iterator interface, in this way, there are four roles in the Iterator mode. The specific class diagram is as follows: it can be seen that the Iterator mode consists of the following roles: the Iterator role (Iterator ): the iterator role defines the interface for accessing and traversing elements. The specific iterator role (Concrete Iteraror) implements the iterator interface and records the current position in the traversal. Aggregate role (Aggregate): The Aggregate role defines the interface specific Aggregate role (Concrete Aggregate) for obtaining the iterator role: the Aggregate role implements the Aggregate role interface. 2.3 After introducing the implementation of the iterator mode, let's take a look at the implementation of the iterator mode. The specific implementation code is as follows: copy code 1 // abstract aggregation Class 2 public interface IListCollection 3 {4 Iterator GetIterator (); 5} 6 7 // Iterator abstract class 8 public interface Iterator 9 {10 bool MoveNext (); 11 Object GetCurrent (); 12 void Next (); 13 void Reset (); 14} 15 16 // specific aggregation class 17 public class ConcreteList: IListCollection 18 {19 int [] collection; 20 public ConcreteList () 21 {22 collection = new Int [] {2, 4, 6, 8}; 23} 24 25 public Iterator GetIterator () 26 {27 return new ConcreteIterator (this ); 28} 29 30 public int Length 31 {32 get {return collection. length;} 33} 34 35 public int GetElement (int index) 36 {37 return collection [index]; 38} 39} 40 41 // specific iterator class 42 public class ConcreteIterator: iterator 43 {44 // to traverse the collection object, the Iterator naturally needs to reference the collection object 45 private ConcreteList _ list; 46 pri Vate int _ index; 47 48 public ConcreteIterator (ConcreteList list) 49 {50 _ list = list; 51 _ index = 0; 52} 53 54 55 public bool MoveNext () 56 {57 if (_ index <_ list. length) 58 {59 return true; 60} 61 return false; 62} 63 64 public Object GetCurrent () 65 {66 return _ list. getElement (_ index); 67} 68 69 public void Reset () 70 {71 _ index = 0; 72} 73 74 public void Next () 75 {76 if (_ index <_ List. length) 77 {78 _ index ++; 79} 80 81} 82} 83 84 // client 85 class Program 86 {87 static void Main (string [] args) 88 {89 Iterator iterator; 90 IListCollection list = new ConcreteList (); 91 iterator = list. getIterator (); 92 93 while (iterator. moveNext () 94 {95 int I = (int) iterator. getCurrent (); 96 Console. writeLine (I. toString (); 97 iterator. next (); 98} 99 100 Console. read (); 101} 102} replica generation Code. The running result of the above Code is also the output of each element in the Set, as shown in figure 3 ,.. NET. NET, the clustering interface and the iterator interface in the iterator mode already exist. The IEnumerator interface plays the iterator role, and the IEnumberable interface plays the abstract aggregation role, there is only one GetEnumerator () method. You can refer to MSDN for the definitions of these two interfaces. In. in. NET 1.0 ,. many collections in the. NET class library have already implemented the iterator mode. You can use the decompilation tool Reflector to view the System under the mscorlib assembly. classes in the Collections namespace. The ArrayList definition code is provided here. You can use the decompilation tool to view the specific implementation code. The specific code is as follows: Copy code 1 public class ArrayList: IList, ICollection, IEnumerable, ICloneable 2 {3 // Fields 4 private const int _ defaultCapacity = 4; 5 private object [] _ items; 6 private int _ size; 7 [NonSerialized] 8 private object _ syncRoot; 9 private int _ version; 10 pr Ivate static readonly object [] emptyArray; 11 12 public virtual IEnumerator GetEnumerator (); 13 public virtual IEnumerator GetEnumerator (int index, int count ); 14 15 // Properties16 public virtual int Capacity {get; set;} 17 public virtual int Count {get;} 18 .............. // For more code, use the decompilation tool Reflector to check 19}. Copy the code and view the source code. You can find that the implementation of the iterator in ArrayList is very similar to the sample code we provided earlier. However, in. NET 2.0, with the yield return keyword, it is easier to implement the iterator mode. For more information about the iterator, see my post. Iv. application scenarios of the iterator mode consider using the iterator mode in the following situations: the system needs to access the content of an aggregate object without exposing its internal representation. The system must support multiple traversal of aggregate objects. The system must provide a unified interface for different aggregation structures. 5. Advantages and disadvantages of the iterator mode because the iterator undertakes the responsibilities of traversing the set, it has the following advantages: the iterator mode allows you to access the content of an aggregate object without exposing its internal representation, that is, iterative abstraction. The iterator mode provides a unified interface for Traversing different set structures, so that the same algorithm can be used to operate on different set structures. The shortcomings of the iterator mode are as follows: the iterator mode changes the structure of the set where the iterator is located while traversing, leading to exceptions. Therefore, the foreach statement can only be used to traverse the set, and the elements in the set cannot be modified at the same time. 6. Here, the content of this blog is over. The iterator mode abstracts an iterator class to separate the traversal behavior of the set object, in this way, the internal structure of the set is not exposed, and external code can transparently access the data in the set. The observer mode will be introduced in a blog.

Related Article

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.