Design mode-iterator mode

Source: Internet
Author: User
Tags reflector

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 the

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

Abstract aggregation class public interface Ilistcollection {Iterator getiterator ();        } Font//Diego Find/Replace with the abstract class public interface Iterator {bool MoveNext ();        Font Size Object GetCurrent ();        void Next ();    void Reset ();        }//Specific aggregation class public class Concretelist:ilistcollection {int[] collection;        Public Concretelist () {collection = new int[] {2, 4, 6, 8};        } public Iterator Getiterator () {Return to New concreteiterator (this); } public int Length {get {return collection. Length;        }} public int getelement (int index) {return collection[index]; }}//Specific iterator class public class Concreteiterator:iterator {//iterator to the collection object for traversal operation, naturally need to reference the collection object private        Concretelist _list;         private int _index;            Public Concreteiterator (concretelist list) {_list = list;        _index = 0; }         public bool MoveNext () {if (_index < _list.            Length) {return true;        } return false; Public Object GetCurrent () {return _list.        GetElement (_index);        } public void Reset () {_index = 0; } public void Next () {if (_index < _list.            Length) {_index++; }}}//client class program {static void Main (string[] args) {Iterator iter            Ator;            Ilistcollection list = new Concretelist (); iterator = list.             Getiterator (); while (iterator. MoveNext ()) {int i = (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, 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:

public class Arraylist:ilist, ICollection, IEnumerable, icloneable{    //Fields    Private Const int _DEFAULTCAPACIT y = 4;    Private object[] _items;    private int _size;    [NonSerialized]    Private object _syncroot;    private int _version;    private static readonly object[] Emptyarray;     Public virtual IEnumerator GetEnumerator ();    Public virtual IEnumerator GetEnumerator (int index, int count);     Properties public    Virtual int capacity {get; set;}    public virtual int Count {get;}    ...//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.

Design mode-iterator mode

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.