“This is the 13th day of my participation in the August Text Challenge.

Introduction to the iterator pattern

The iterator pattern is a behavioral design pattern that allows you to iterate through all the elements of a collection without exposing the underlying representation of the collection (list, stack, tree, etc.).

The iterator pattern satisfies the single-responsibility and open-closed principle, and external callers do not need to know the traversal differences in the use of any different data structures.

The main idea of the iterator pattern is to extract the traversal behavior of a collection into a single iterator object.

In addition to implementing its own algorithm, the iterator encapsulates all the details of the traversal operation, such as the current position and the number of remaining elements at the end, as well as providing a basic method for retrieving collection elements. The client can keep calling this method until it returns nothing (all elements have been iterated), and all iterators must implement the same interface (client code is compatible with any type of collection or traversal as long as there are appropriate iterators).

Structure of an iterator

  • Iterator interface: Declares the operations needed to traverse a collection. (Get the next element, get the current position, restart the iteration, etc.)

  • Concrete iterator: A specific algorithm that implements traversal of a set. (Iterators must track the progress of their own traversal.)

  • Collection interface: Declares one or more methods to get iterators compatible with collections. (The type of the return method must be declared as an iterator interface, so concrete collections can return various kinds of iterators.)

  • Concrete collection: A specific concrete iterator class is returned when the client requests an iterator.

  • Client: Interacts with both collections and iterators through interfaces. This eliminates the need for the client to be coupled to a concrete class, allowing the same client code to use a variety of different collections and iterators.

Application scenarios

  • When there is a complex data structure behind the collection and you want to hide the complexity from the client.
  • You want to avoid repetitive code traversal in your program
  • When program code can traverse different or even unpredictable data structures.

implementation

Declare the iterator interface

2. Declare a collection interface and describe a method for getting iterators. The return value must be the iterator interface.

3. Implement concrete iterator classes for collections that you want to traverse using iterators.

Implement the collection interface in your collection class.

5. Replace all collection traversal code with iterators on the client.

Demo

With the help of iterators, clients can iterate over elements in different collections in a similar way with an iterator interface.

Iterator pattern discrimination

  • Iterators can be easily identified by navigation methods (Next and Previous).
  • Client code that uses iterators may not have direct access to the collection it is iterating over (the two are completely separate).

An iterator pattern for sorting collections of people is listed below.

Staff iterator

/// <summary> /// staff iterator /// inherits interface IEnumerator, displays the implementation of Current, MoveNext, Reset methods. /// </summary> abstract class PeopleIterator:IEnumerator { public abstract int Key(); public abstract object Current(); public abstract bool MoveNext(); public abstract void Reset(); object IEnumerator.Current { get { return Current(); }}}Copy the code

Abstract collection iterators and their implementation

/// </summary> public Abstract Class AggregateIterator :IEnumerable {/// <summary> /// /// </summary> // <returns></returns> public abstract IEnumerator GetEnumerator(); } / / / < summary > / / / set the iterator class specific sorting logic here / / / write / / / < summary > class AlphabeticalOrderIterator: PeopleIterator { private PeopleCollection _collection; private int _position = -1; private bool _reverse = false; public AlphabeticalOrderIterator(PeopleCollection collection,bool reverse=false) { this._collection = collection; _reverse = reverse; if (reverse) { _position = collection.getItems().Count; }} /// <summary> // Current value /// </summary> /// <returns></returns> public Override object Current() {return this._collection.getItems()[_position]; Public override int Key() {return this._position; return this._position; } /// </summary> // </returns> public override bool MoveNext() {int updatedPosition = this._position + (this._reverse ? 1:1); if (updatedPosition >= 0 && updatedPosition < this._collection.getItems().Count) { this._position = updatedPosition; return true; } else { return false; }} /// <summary> /// Reset /// </summary> public override void Reset() {this._position = this._reverse? this._collection.getItems().Count - 1 : 0; }}Copy the code

A specific collection of people and its Main() method validation

/// </summary> public Class PeopleCollection :AggregateIterator {List<string> _collection = new List<string>(); bool _direction = false; public void ReverseDirection() { _direction = ! _direction; } public List<string> getItems() { return _collection; } public void AddItem(string item) { _collection.Add(item); } public override IEnumerator GetEnumerator() { return new AlphabeticalOrderIterator(this,_direction); } } class Program { static void Main(string[] args) { var collection = new PeopleCollection(); Collection. AddItem (" five o "); Collection. AddItem (" six o "); Collection. AddItem (" seven o "); Console.WriteLine(" Check "); foreach (var item in collection) { Console.WriteLine(item); } console. WriteLine(" reverse order "); collection.ReverseDirection(); foreach (var item in collection) { Console.WriteLine(item); } Console.ReadKey(); }}Copy the code

Iterator mode is a little difficult to understand, because usually when using collections, various languages have already listed the various operation methods of collections, callers can call intuitively. Therefore, we should practice and think more when we understand the idea of its design mode.

Some things will come to be understood naturally if you have seen and done much.

Small remarks

Life is short, I don’t want to go after what I can’t see, I just want to catch what I can see.

Original is not easy, give a attention.

I am Hui, thank you for reading, if it is helpful to you, please pay attention to, like, forward thank you.